Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 57 ยท Working with Data

Plotting NumPy and pandas Data

Turn arrays and DataFrames into charts. Use meshgrid, DataFrame columns, df.plot with ax=, groupby loops, pivot tables and datetime indexes.

Matplotlib was built to draw NumPy arrays, and pandas builds its own plotting on top of Matplotlib. That means you can mix the two freely: compute with NumPy or pandas, draw with Matplotlib, and keep full control of the result. This lesson shows the handful of patterns you will use again and again.

You will plot arrays and 2D grids, send DataFrame columns into ax.plot, use df.plot while handing it an Axes you created yourself, loop over groupby results to draw one line per group, pivot a table into grouped bars and plot a datetime index. If you want the pandas point of view, Plotting with pandas and Charts for Analysis cover the same ground from the DataFrame side.

Data in, chart out

NumPy arrays Passed straight to plot, scatter, imshow.
pandas objects Columns and indexes work as x and y.
Your own Axes df.plot(ax=ax) keeps full control.

Everything ends up as the same Matplotlib artists.

1 / 2

NumPy arrays: one-dimensional and two-dimensional

Any NumPy array can go straight into ax.plot. Build x with np.linspace or np.arange and compute y with a vectorized expression; there is no loop.

When y is a 2D array, ax.plot(x, Y) draws one line per column. That makes it easy to plot many curves at once.

Python One call, several curves

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.

Output shapes: x shape: (200,) and Y shape: (200, 3). The rule to remember is that the first dimension must match the length of x; each column is a series. If your data is stored one series per row, transpose it with Y.T first.

Grids with meshgrid

Functions of two variables, such as a height over a surface, need a grid of (x, y) coordinates. np.meshgrid turns two 1D axes into two 2D arrays, so you can evaluate the function on every grid point at once. Then contourf (filled contours) or pcolormesh draws it.

Python A function of two variables

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.

Shapes: ys has 100 entries and xs has 150, so every grid array is (100, 150), rows follow y and columns follow x. Mixing those up is the most common meshgrid bug. See Heatmaps and Images for more on imshow and contours.

DataFrame columns on an Axes

Matplotlib functions accept pandas Series anywhere they accept arrays. If the index is meaningful (dates, years), pass it as x with df.index.

Python Columns as x and y

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.

There is a handy shortcut: ax.plot("year", "solar", data=df) looks the names up in the DataFrame. It also works for scatter. For a column that goes on the y axis and the labels come from the data, the explicit form above is easier to read in longer code.

df.plot with your own Axes

df.plot() is a thin wrapper that calls Matplotlib for you. By default it creates its own figure, but you can hand it an existing Axes with ax=. That is the bridge between the two worlds: pandas does the data work, you keep control of layout and styling.

Python df.plot inside a subplot grid

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.

df.plot returns the Axes it drew on, so you can keep customizing with normal Matplotlib calls such as set_title and set_ylabel. Useful arguments are kind (or the df.plot.bar, .hist, .box methods), x, y, subplots=True, logy=True and figsize.

If a pandas plot "ignores" your figure and opens a new one, you forgot ax=. Always pass ax= when you build a layout yourself.

Loops over groupby results

To draw one line (or one histogram, or one box) per category, loop over a groupby. Each iteration gives you the group key and the sub-DataFrame.

Python One line per group

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 printed lines show Cairo rows: 12, Madrid rows: 12 and Oslo rows: 12, because groupby sorts group keys alphabetically; the legend follows the same order. If you want a specific order, loop over a list of keys and select with df[df["city"] == name].

For aggregated values, summarise first and plot second: df.groupby("city")["temp"].mean() is a Series whose index holds the cities, ready for ax.bar(series.index, series.values).

Pivot to grouped bars

Grouped bars need a table with one row per category and one column per group. pivot_table makes exactly that, and then you draw one bar series per column. With Matplotlib you compute the bar offsets yourself, which gives you full control over spacing.

Python pivot_table into grouped bars

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 trick is the offset: with three bars per region, the middle bar sits on the tick and the others are shifted by one bar width. Setting ax.set_xticks(positions, regions) uses the two-argument form that sets positions and labels together. Shortcut: table.plot.bar(ax=ax) does the same offset math for you, at the cost of less control.

A datetime index

Pandas parses dates into Timestamp objects, and Matplotlib knows how to draw them. If you pass a DatetimeIndex as x, you get a date axis with sensible tick labels automatically.

Python A date index on the x axis

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.

fig.autofmt_xdate() rotates and aligns the date labels so they do not overlap. The weekly pattern in the data is hidden by the smoothed line, which makes the upward trend obvious. The next lessons go further into formatting dates: Dates and Time Series Charts.

Which API to use?

You have Reach for
A NumPy array or two ax.plot(x, y), ax.scatter, ax.imshow
A 2D grid of values meshgrid plus contourf or pcolormesh
A tidy DataFrame, quick look df.plot(...)
A DataFrame in a layout you control df.plot(ax=ax) or ax.plot(df["a"], df["b"])
One series per category loop over df.groupby(...)
Categories by groups of bars pivot_table then offset bars or .plot.bar(ax=ax)

Both APIs create the same Matplotlib objects, so you can always switch halfway: draw with pandas, then polish with ax.set_* and ax.annotate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ax.plot(x, Y) draw when Y has shape (200, 3) and x has 200 values?

    For a 2D y array, plot treats each column as a separate series that shares the same x values.
  2. 2. Why do you pass ax=ax to df.plot when you are building your own subplot layout?

    ax= tells pandas which existing Axes to draw on. Without it, pandas creates its own figure and your layout stays empty.
  3. 3. With xs of length 150 and ys of length 100, what is the shape of the arrays returned by np.meshgrid(xs, ys)?

    With the default indexing, rows follow y and columns follow x, so each array has shape (len(ys), len(xs)) = (100, 150).
  4. 4. How do you get one line per category from a long DataFrame?

    groupby yields each group's key and sub-DataFrame, so you can draw one line per group and label it with the key.
  5. 5. What does fig.autofmt_xdate() do?

    It rotates the x tick labels and right-aligns them, which is the usual fix for crowded date labels.

Summary

  • NumPy arrays and pandas Series go directly into Matplotlib calls; a 2D y array draws one line per column.
  • np.meshgrid builds coordinate grids for contourf and pcolormesh; shapes are (len(y), len(x)).
  • ax.plot(df["a"], df["b"]) or ax.plot("a", "b", data=df) plots DataFrame columns.
  • df.plot(ax=ax) lets pandas draw while you control the layout and styling.
  • Loop over groupby for one series per group; summarise first and plot second.
  • pivot_table shapes data for grouped bars, with bar offsets computed from the bar width.
  • A DatetimeIndex gives a date axis, and fig.autofmt_xdate() tidies the labels.

Next: Dates and Time Series Charts