Plotting from Pandas
Python · Data Visualization
Theory
pandas DataFrames and Series have a built-in .plot that calls matplotlib for you. The index becomes the x-axis and each numeric column becomes a series, so df.plot() on a table indexed by month draws one line per column, with a legend. Pick the chart with kind= or the accessor style: df.plot.bar(), df.plot.barh(), df.plot.hist(bins=10), df.plot.box(), df.plot.scatter(x='a', y='b') and df.plot.pie(y='col').
The usual pattern is aggregate first, then plot: orders.groupby('city')['amount'].sum().sort_values().plot.barh() turns raw rows into a ranked bar chart in one line. stacked=True stacks bars, subplots=True gives one panel per column, and title=, figsize= and color= pass straight through. .plot returns a matplotlib Axes, so you can keep customising it, and ax=ax draws into an Axes you created with plt.subplots.
Why we use it
Most analysis data already lives in DataFrames. df.plot turns a groupby result or a pivot table into a chart in one line, which is ideal for quick exploration before polishing a final figure.
When to use it
Use df.plot for fast exploratory charts straight from tables and groupby results. Switch to matplotlib calls on the returned Axes for fine-tuning, and to seaborn when you want grouped statistical charts with little code.
How it works
- DataFrame of raw rows
- Already one row per x value? Yes: Plot directly. No: groupby / pivot_table to aggregate first.
- Sort if it is a ranking
- Call .plot.bar(), .plot(), .plot.hist() ...
- Customise the returned Axes (labels, limits)
- Quick chart from the table
Syntax
df.plot(x='col', y=['a', 'b'])
df.plot.bar(stacked=True) df.plot.barh() df.plot.hist(bins=10)
df.plot.scatter(x='a', y='b')
ax = s.plot.bar(title='...'); ax.set_ylabel('...')Example
totals = orders.groupby('city')['amount'].sum()
ax = totals.sort_values().plot.barh(title='Sales by city')
ax.set_xlabel('Rs')Key points
- The index becomes the x-axis; each numeric column a series
- Aggregate (groupby, pivot_table) first, then .plot
- kind= or accessors: .plot.bar, .plot.hist, .plot.scatter
- stacked=True and subplots=True work on DataFrames
- .plot returns a matplotlib Axes for further tweaks