ZetCode

Pandas Plotting

last modified November 17, 2026 Python 3.15

Pandas can turn a DataFrame or Series into a chart with a single method call. The plot method is a thin convenience layer built on top of Matplotlib, the underlying plotting library; it passes the data to Matplotlib and returns the axes so they can be customised further. If you want full control of a figure, the Matplotlib line chart tutorial and the rest of that section cover the same machinery directly.

The scripts below use the non-interactive Agg backend, which is set before pyplot is imported so the code runs without a display. Each script saves its figure to a PNG file on disk and prints a short confirmation; the output blocks therefore contain printed text rather than the images themselves.

A line plot

A line plot connects data points in order and is the usual choice for trends over time or another ordered variable. Here the x and y arguments pick the columns to draw, while title, xlabel and ylabel add text and figsize sets the figure's width and height in inches.

plot_line.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'month': [1, 2, 3, 4], 'sales': [12, 18, 15, 24]})
ax = df.plot(kind='line', x='month', y='sales', title='Monthly sales',
             xlabel='Month', ylabel='Sales', figsize=(6, 4))
plt.gcf().savefig('/tmp/opencode/agentH_plot_line.png')
print('Saved /tmp/opencode/agentH_plot_line.png')

The chart is drawn in memory and then written to the PNG file with savefig; the printed line simply confirms that the file was created. Calling matplotlib.use('Agg') before importing pyplot matters: once pyplot is imported, the backend is fixed.

$ python plot_line.py
Saved /tmp/opencode/agentH_plot_line.png

A bar plot

A bar plot compares categories by drawing one rectangle per category, with the height showing the value. It is appropriate when the labels have no natural order. The same labelling arguments work here, and the categories are taken from the column named by x.

plot_bar.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'city': ['A', 'B', 'C', 'D'], 'population': [5, 8, 3, 6]})
ax = df.plot(kind='bar', x='city', y='population', title='Population by city',
             xlabel='City', ylabel='Population (millions)', figsize=(6, 4))
plt.gcf().savefig('/tmp/opencode/agentH_plot_bar.png')
print('Saved /tmp/opencode/agentH_plot_bar.png')

Four bars are drawn, one for each city, and the result is saved alongside the first image. The ax variable holds the Matplotlib axes object, so further Matplotlib calls can adjust ticks, colours or legends after the plot has been created.

$ python plot_bar.py
Saved /tmp/opencode/agentH_plot_bar.png

A histogram

A histogram shows the distribution of a single numeric column: the values are sorted into ranges called bins, and each bar shows how many values fell into that bin. It differs from a bar plot, where each bar represents a named category rather than a range of numbers. The bins argument controls how many ranges are used.

plot_hist.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

values = pd.Series([1, 2, 2, 3, 3, 3, 4, 4, 5])
ax = values.plot(kind='hist', bins=5, title='Value distribution',
                 xlabel='Value', ylabel='Frequency', figsize=(6, 4))
plt.gcf().savefig('/tmp/opencode/agentH_plot_hist.png')
print('Saved /tmp/opencode/agentH_plot_hist.png')

The Series has nine values and five bins, so the bars show how those values are spread from 1 to 5. Histograms are called directly on a Series here, but DataFrames support them as well.

$ python plot_hist.py
Saved /tmp/opencode/agentH_plot_hist.png

A box plot

A box plot summarises a distribution with its median, quartiles and whiskers, and marks values that lie far from the rest as outliers. Drawing one box per column makes it easy to compare the spread of several numeric columns at a glance.

plot_box.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': [10, 12, 11, 13, 12], 'B': [20, 18, 22, 19, 21]})
ax = df.plot(kind='box', title='Box plot of A and B',
             ylabel='Value', figsize=(6, 4))
plt.gcf().savefig('/tmp/opencode/agentH_plot_box.png')
print('Saved /tmp/opencode/agentH_plot_box.png')

Two boxes appear, one for column A and one for B. There is no meaningful horizontal axis here, so only the vertical axis is labelled.

$ python plot_box.py
Saved /tmp/opencode/agentH_plot_box.png

A scatter plot

A scatter plot places one dot at the intersection of two numeric values and is used to look for a relationship between them. Unlike the line plot, no connection is drawn between the points. Both coordinates come from columns chosen with x and y.

plot_scatter.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'height': [150, 160, 170, 180, 190],
                   'weight': [50, 55, 65, 75, 85]})
ax = df.plot(kind='scatter', x='height', y='weight', title='Height vs weight',
             xlabel='Height (cm)', ylabel='Weight (kg)', figsize=(6, 4))
plt.gcf().savefig('/tmp/opencode/agentH_plot_scatter.png')
print('Saved /tmp/opencode/agentH_plot_scatter.png')

Five points are drawn, one per row of the DataFrame. The upward pattern shows that the two columns rise together in this small sample; the plot itself simply places the pairs on the axes.

$ python plot_scatter.py
Saved /tmp/opencode/agentH_plot_scatter.png

Multiple subplots

A subplot is one of several separate axes drawn inside a single figure. Passing subplots=True gives each column its own panel, which is useful for comparing series with different scales. A list of titles labels the panels, figsize makes the figure tall enough for both, and tight_layout keeps the labels from overlapping.

plot_subplots.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'sales': [12, 18, 15, 24], 'costs': [8, 9, 10, 11]})
axes = df.plot(subplots=True, kind='line', figsize=(6, 6),
               title=['Sales', 'Costs'])
fig = plt.gcf()
fig.tight_layout()
fig.savefig('/tmp/opencode/agentH_plot_subplots.png')
print('Saved /tmp/opencode/agentH_plot_subplots.png')

The two panels are stacked vertically, one titled Sales and the other Costs, and saved as a single image. The variable axes holds the collection of axes; here we fetch the current figure with plt.gcf() to adjust and save the whole image at once.

$ python plot_subplots.py
Saved /tmp/opencode/agentH_plot_subplots.png

A stacked area chart

An area chart fills the space under each line, and a stacked area chart piles the series on top of one another so the total is visible as well as the parts. Pandas exposes this through the dedicated plot.area accessor, which is a shortcut for plot(kind='area').

plot_area.py
import matplotlib
matplotlib.use('Agg')

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'A': [1, 2, 3, 4], 'B': [4, 3, 2, 1]})
ax = df.plot.area(title='Stacked area chart', xlabel='Index', ylabel='Value',
                  figsize=(6, 4))
plt.gcf().savefig('/tmp/opencode/agentH_plot_area.png')
print('Saved /tmp/opencode/agentH_plot_area.png')

The two filled regions add up to five at every point, so the top edge is flat while the boundary between the regions moves. The figure is saved to disk and the confirmation is printed, just as in the earlier examples.

$ python plot_area.py
Saved /tmp/opencode/agentH_plot_area.png

Source

Pandas DataFrame.plot Documentation, Pandas Visualization Documentation, and Matplotlib savefig Documentation

In this article we have drawn line, bar, histogram, box, scatter and stacked area charts with Pandas' plot method, arranged panels with subplots, and labelled figures with title, xlabel, ylabel and figsize. For the underlying library see the Matplotlib tutorial, and for preparing data before plotting see Pandas grouping data.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pandas tutorials.