Q&A library Python

How do I plot straight from a pandas DataFrame?

Python Intermediate matplotlibpandasplotting

Short answer

Call .plot() on a DataFrame or Series, choosing the chart with the kind argument. It uses matplotlib underneath and returns an Axes, so you can fine-tune the result with matplotlib.

The short version

Call .plot() directly on a Series or DataFrame and pass kind to choose the chart type. Pandas draws it with matplotlib and returns the Axes object, so you can then adjust titles, labels and limits using matplotlib as normal. This is the fastest route from a table to a chart.

The basics

import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "city": ["Leeds", "Bath", "York"],
    "amount": [10, 20, 15],
}).set_index("city")

ax = df.plot(kind="bar")
ax.set_ylabel("Amount")
plt.show()

The index becomes the x axis and each column becomes a series, which is why setting a meaningful index first usually gives the chart you want.

Chart types

kind accepts "line" (the default), "bar", "barh", "hist", "box", "scatter", "area" and "pie".

df["amount"].plot(kind="hist", bins=10)     # distribution
df.plot(kind="scatter", x="temp", y="sales")  # needs x and y named

scatter is the one that needs explicit x and y, because it plots one column against another rather than against the index.

The index becomes the x axis

This is the key mental model. For a time series, set the dates as the index and pandas labels the x axis with them automatically.

ts.set_index("date")["amount"].plot()

If your chart's x axis shows meaningless row numbers, the usual cause is that the column you wanted on the axis is still a column rather than the index.

It returns a matplotlib Axes

Everything you know about matplotlib still applies, because that is what is doing the drawing.

ax = df.plot(kind="bar")
ax.set_title("Amount by city")
ax.set_ylim(0, 25)
ax.figure.savefig("chart.png")

So pandas plotting is not a separate system; it is a convenient shortcut that hands you back a normal matplotlib object for the finishing touches.

Plotting grouped results

Because groupby results are DataFrames, they plot directly, which makes a summary chart a one-liner.

df.groupby("city")["amount"].sum().plot(kind="bar")

This is the pattern that makes pandas plotting genuinely useful: aggregate, then plot the result, with no intermediate reshaping.

When to reach for something else

Pandas plotting is ideal for a quick look during analysis. For a polished figure, or for splitting by category with a legend, seaborn does more with less code. And for full control over a publication figure, drop down to matplotlib directly. Use .plot() for exploration, and the others when the chart itself is the deliverable.

Need this solved on your own data?

The library is free and always will be. When the problem is bigger than an answer, we take on the work.

Start a project