TExcelTAD
Home › Matplotlib › Plotting pandas Data

Plotting pandas Data

Most real data lives in pandas DataFrames. pandas has a built-in .plot() accessor that calls Matplotlib for you, using the index as the x axis and the column names as labels. The result is an ordinary Matplotlib Axes, so everything from this course still applies.

DataFrame.plot()

python · try it yourself
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
    "coffee": [520, 480, 510, 450, 430, 400],
    "tea": [210, 220, 205, 230, 250, 270],
    "juice": [90, 95, 120, 150, 190, 240],
}).set_index("month")

ax = df.plot(marker="o", title="Drinks sold per month")
ax.set_ylabel("Cups")
plt.show()

print(df)
print("Returned:", type(ax).__name__, "with", len(ax.lines), "lines")
       coffee  tea  juice
month
Jan       520  210     90
Feb       480  220     95
Mar       510  205    120
Apr       450  230    150
May       430  250    190
Jun       400  270    240
Returned: Axes with 3 lines

One line per column, a legend from the column names, and the index on the x axis, all without writing a loop.

Choosing the kind

The kind argument (or the shortcut methods df.plot.bar(), df.plot.hist(), …) selects the chart type:

kind= Shortcut Chart
"line" .plot.line() line chart (default)
"bar" / "barh" .plot.bar() vertical / horizontal bars
"hist" .plot.hist() histogram
"box" .plot.box() box plot
"area" .plot.area() stacked area
"pie" .plot.pie() pie chart (Series or subplots=True)
"scatter" .plot.scatter(x=, y=) scatter (DataFrame only)
"kde" .plot.kde() smoothed density (needs SciPy)
python · try it yourself
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame({
    "coffee": [520, 480, 510, 450, 430, 400],
    "tea": [210, 220, 205, 230, 250, 270],
    "juice": [90, 95, 120, 150, 190, 240],
}, index=["Jan", "Feb", "Mar", "Apr", "May", "Jun"])

fig, axes = plt.subplots(1, 2, figsize=(10, 4), layout="constrained")
df.plot.bar(ax=axes[0], rot=0, title="Grouped bars")
df.plot.bar(ax=axes[1], stacked=True, rot=0, title="Stacked bars")
axes[1].set_ylim(0, 1100)
axes[1].legend(ncols=3, loc="upper center")
plt.show()

print("Totals per month:")
print(df.sum(axis=1))
Totals per month:
Jan    820
Feb    795
Mar    835
Apr    830
May    870
Jun    910
dtype: int64

The ax= argument tells pandas which existing Axes to draw on, so pandas plots fit into your own subplot layouts. rot=0 keeps the tick labels horizontal.

Scatter plots and colour by column

plot.scatter takes column names for x, y, and optionally c (colour) and s (size):

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(8)
cars = pd.DataFrame({"weight": rng.uniform(900, 2200, 60)})
cars["power"] = cars["weight"] * 0.07 + rng.normal(0, 15, 60)
cars["consumption"] = 2 + cars["weight"] / 400 + rng.normal(0, 0.4, 60)

ax = cars.plot.scatter(x="weight", y="power", c="consumption", cmap="viridis",
                       s=40, figsize=(7, 4.5))
ax.set(xlabel="Weight (kg)", ylabel="Power (kW)")
plt.show()

print(cars.describe().round(1))
       weight  power  consumption
count    60.0   60.0         60.0
mean   1479.8  104.3          5.7
std     332.3   26.6          0.9
min     921.8   53.0          3.8
25%    1228.1   89.7          5.0
50%    1431.5  105.5          5.6
75%    1696.2  117.3          6.3
max    2185.4  181.8          8.2

Grouping, then plotting

The real power comes from combining pandas' data wrangling with plotting. Here we group raw orders by category and plot the result:

python · try it yourself
import io
import pandas as pd
import matplotlib.pyplot as plt

csv = io.StringIO("""date,category,amount
2024-01-03,books,24.0
2024-01-05,games,59.9
2024-01-09,books,12.5
2024-01-14,music,9.9
2024-01-20,games,19.9
2024-02-02,books,31.0
2024-02-11,music,14.5
2024-02-15,games,69.0
2024-02-21,books,8.0
2024-02-28,music,11.0
""")
orders = pd.read_csv(csv, parse_dates=["date"])
orders["month"] = orders["date"].dt.strftime("%Y-%m")

table = orders.pivot_table(index="month", columns="category", values="amount", aggfunc="sum")
print(table)

ax = table.plot.barh(stacked=True, figsize=(7, 3), title="Revenue by month and category")
ax.set_xlabel("€")
ax.legend(loc="center left", bbox_to_anchor=(1.01, 0.5))
plt.tight_layout()
plt.show()
category  books  games  music
month
2024-01    36.5   79.8    9.9
2024-02    39.0   69.0   25.5

io.StringIO lets read_csv read text from a string, so the example needs no file. With a real file you would write pd.read_csv("orders.csv").

Time series with a DatetimeIndex

When the index holds dates, pandas formats the x axis as dates automatically, and methods like rolling() make smoothing easy:

python · try it yourself
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

idx = pd.date_range("2024-01-01", periods=120, freq="D")
rng = np.random.default_rng(13)
visits = pd.Series(500 + np.arange(120) * 2 + rng.normal(0, 60, 120), index=idx, name="visits")

ax = visits.plot(alpha=0.4, label="daily", figsize=(8, 3.5))
visits.rolling(7).mean().plot(ax=ax, lw=2, label="7-day average")
ax.legend()
ax.set_ylabel("Visits")
plt.tight_layout()
plt.show()

print(visits.resample("MS").mean().round(1))
2024-01-01    550.7
2024-02-01    599.1
2024-03-01    636.7
2024-04-01    712.2
Freq: MS, Name: visits, dtype: float64

Tip: df.plot(subplots=True, layout=(2, 2), sharex=True) draws each column in its own panel. Since pandas returns Matplotlib objects, you can always fine-tune the result with ax.set_... calls.

Test yourself

What does df.plot() use for the x axis by default?

  1. The first column
  2. The DataFrame's index
  3. A range 1..n always
  4. The column names

How do you draw a pandas plot into an existing subplot axes[1]?

  1. df.plot(subplot=1)
  2. df.plot(ax=axes[1])
  3. axes[1].plot(df) is the only way
  4. df.plot().move(axes[1])

What does df.plot.bar(stacked=True) produce?

  1. One bar per column
  2. Bars for each row with the columns stacked on top of each other
  3. A stacked area chart
  4. A histogram