Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 64 ยท Visualisation

Plotting with pandas

Draw charts straight from a DataFrame with df.plot. Make line, bar, histogram, box, scatter, area and pie charts, add titles and labels, and use subplots.

A table of numbers hides patterns that a chart shows at a glance. pandas has plotting built in: every Series and DataFrame has a .plot accessor that hands your data to matplotlib and returns the matplotlib objects, so you get a chart in one line and full control when you need it.

In this lesson you will draw the main chart kinds with df.plot, label them, put several charts on one figure and learn how pandas and matplotlib share the work. If you have not met matplotlib yet, the Python matplotlib lesson covers figures and axes in more depth. The next lesson, Charts for Analysis, uses these tools on real questions.

Note: the first Run downloads matplotlib, so expect a short wait. Figures that are still open at the end of your code appear below the editor as images, and plt.show() works as you would expect.

How df.plot works

df.plot(...) is a thin wrapper. pandas decides what goes on the x axis and what becomes a line or bar, then calls matplotlib. The result is a matplotlib Axes object, the canvas that holds one chart. You can keep it, draw more on it, or pass an existing one in with ax=.

flowchart LR
    A["DataFrame"] --> B["df.plot(kind=...)"]
    B --> C["matplotlib Axes"]
    C --> D["Figure"]
    D --> E["Image in the browser"]

pandas prepares the data and the chart type; matplotlib draws it. The Axes you get back lets you add titles, labels and extra layers.

The default chart is a line chart. The index goes on the x axis and every numeric column becomes one line, with a legend built from the column names.

Python A line chart from a DataFrame

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The title= and marker= arguments go straight through to matplotlib. The returned ax lets you call methods such as set_xlabel() and set_ylabel(). Always label axes and say what the unit is; a chart without labels makes the reader guess.

Choosing the kind of chart

Select a chart with kind= or, more readable, with a method: df.plot.bar() is the same as df.plot(kind="bar"). These are the kinds you will use most.

Kind Method Good for
Line df.plot.line() Values that change over an ordered axis such as time
Bar df.plot.bar() / barh() Comparing categories
Histogram df.plot.hist() The distribution of one numeric column
Box df.plot.box() Median, spread and outliers, side by side
Scatter df.plot.scatter(x, y) The relationship between two numeric columns
Area df.plot.area() Totals that are made of parts over time
Pie Series.plot.pie() A few shares of a whole

Bar charts treat the index as category labels, so they pair naturally with the result of a groupby(). Stacked bars show parts of a total.

Python Bar charts: grouped, stacked and horizontal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Here plt.subplots(1, 3) creates one figure with three Axes in a row, and each plot call draws into one of them through ax=. That is the standard way to place several pandas charts on one figure. rot=0 keeps the tick labels horizontal.

Distributions: hist, box and scatter

Three kinds describe numbers rather than categories. A histogram counts how many values fall into each bin. A box plot draws the median, the middle half of the data and the points that look unusual. A scatter plot puts one column on each axis so you can see whether they move together.

To make the data repeatable we use a random generator with a fixed seed.

Python Histogram, box plot and scatter plot

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

bins=15 controls how many bars the histogram uses. Too few bins hide the shape, too many make it noisy, so try a few values. In the scatter plot alpha=0.6 makes points semi-transparent, which helps when they overlap. Notice that the two columns have very different scales in the box plot; when columns do not share a unit, plot them separately.

Crowded scatter plots: hexbin, bins and figure size

With thousands of points a scatter plot turns into a solid blob. Two fixes: lower alpha so overlaps get darker, or switch to a hexbin plot, which divides the plane into hexagons and colors each by how many points fall inside it. df.plot.hexbin(x=, y=, gridsize=20) does that; gridsize is the number of hexagons across (more means finer cells) and cmap chooses the color scale. For a histogram, bins=50 gives a smoother outline than the default of 10, and bins also accepts a list of edges.

Every plot call takes figsize=(width, height) in inches. Make it wider for time series with many dates, taller for horizontal bars. When you draw into your own axes (as in the example), set the size once on plt.subplots(figsize=...) instead.

Python Hexbin, bins and figure size

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The hexbin makes the dense core and the sparse tails visible at once, which the plain scatter hides.

Area and pie charts

An area chart is a line chart with the space under the line filled. Stacked areas (the default for area()) are useful when the parts add up to a meaningful total. A pie chart works only on a Series, because it needs one value per slice, and only when there are a handful of slices that add up to a whole.

Python Area and pie charts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pie charts are easy to misread because people compare angles poorly. If you have more than four or five categories, or the slices are similar in size, a sorted bar chart is almost always clearer.

Titles, labels, colors and legends

Common arguments work across most kinds:

  • title=, xlabel=, ylabel= set the text around the chart.
  • figsize=(width, height) sets the size in inches.
  • color= takes one color or a list; colormap= takes a matplotlib colormap name.
  • legend=False removes the legend, useful when there is a single series.
  • grid=True adds grid lines; xlim= and ylim= set axis limits.
  • logy=True uses a logarithmic y axis for data that spans orders of magnitude.

Anything pandas does not expose is available on the Axes you get back, for example ax.axhline(100, linestyle="--") for a target line or ax.annotate(...) for a note.

One chart per column with subplots

Columns on different scales do not belong on one set of axes. Set subplots=True and pandas draws one small chart per column and stacks them with a shared x axis.

Python subplots=True and a reference line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With subplots=True the return value is an array of Axes, one per column, so you can still decorate individual panels. Here a dashed line marks 50 mm of rain on the middle chart.

Saving a figure

On your own computer you save a figure with fig.savefig("chart.png", dpi=150). The browser editors cannot write files you can download, but you can see how it works with an in-memory buffer:

Python Saving a figure to memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

ax.figure is the Figure that holds the Axes. Call plt.close(fig) when you create many figures in a loop, otherwise matplotlib keeps them all in memory.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does df.plot() return?

    The call returns the Axes it drew on, so you can keep customising the chart, for example with set_xlabel() or axhline().
  2. 2. You want several pandas charts side by side in one figure. What do you do?

    plt.subplots() creates the figure and the Axes, and the ax= argument tells each df.plot call where to draw.
  3. 3. Which chart kind is a good fit for the distribution of a single numeric column?

    A histogram groups values into bins and shows how many fall into each, which reveals the shape of the distribution.
  4. 4. Your DataFrame has columns on very different scales, such as temperature in degrees and rainfall in millimetres. Which option helps?

    subplots=True gives each column its own panel and y axis, so one column does not squash the others.

Summary

  • df.plot and Series.plot wrap matplotlib and return the Axes they draw on.
  • Pick the chart with kind= or with .plot.bar(), .plot.hist(), .plot.box(), .plot.scatter(), .plot.area() and .plot.pie().
  • Bars compare categories, histograms and box plots show distributions, scatter plots show relationships, lines show change over an ordered axis.
  • Combine charts with plt.subplots() and ax=, or use subplots=True for one panel per column.
  • Always label axes and give the chart a title; use the returned Axes for anything pandas does not expose.

Next: Charts for Analysis