Sub topic 4
Line and area charts
This chapter assumes you can build a DataFrame, that you know the set_index and x/y arguments from the previous chapters, and that matplotlib is installed.
Line charts
kind="line" is the default, so df.plot() and df.plot.line() give the same chart. Each numeric column becomes one line. The index supplies the x values. If the index is a plain 0, 1, 2... range, the x axis shows row numbers, so move your category or date column into the index first.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr", "May"],
"sales": [120, 135, 150, 170, 160],
"costs": [80, 90, 95, 110, 105],
})
df.set_index("month").plot(
marker="o",
linestyle="--",
title="Sales and costs",
)
plt.show()Extra keyword arguments such as marker and linestyle go to matplotlib's line drawing. You can also pass style=["o-", "s--"], which gives one format string per column.
To plot a single column against another, use x and y:
df.plot(x="month", y="sales", marker="o", legend=False)
plt.show()Missing values (NaN) leave a gap in a line chart. Pandas does not connect the points on either side. If you want a continuous line, fill or interpolate the data first, for example with df.interpolate().
Area charts
An area chart is a line chart with the space under each line filled. Use kind="area" or df.plot.area().
wide = df.set_index("month")
wide.plot.area(title="Stacked (default)")
wide.plot.area(stacked=False, alpha=0.4, title="Overlapping")
plt.show()The default is stacked=True. Each column is drawn on top of the one below it, so the top edge shows the total. This suits parts of a whole, such as revenue by product. Pandas also fills NaN values with 0 in a stacked area chart, so a gap becomes a drop to zero.
With stacked=False the areas overlap, and each one starts at zero. Set alpha below 1 so the shapes behind stay visible.
Choosing between them
Common problems
- Stacked areas with negative values. Negative numbers stack below zero and the top edge no longer equals the total. Use a line chart or
stacked=Falseinstead. - Too many columns. Ten lines or stacked layers are hard to read. Select the columns you need with
df[["sales", "costs"]]. - Different scales. A column in the millions flattens one in the tens. Plot them separately, or use
secondary_y="costs"to draw that column on a right-hand axis. - Row numbers on the x axis. You forgot
set_indexorx=.
Exercise
You have a DataFrame with columns "quarter", "north" and "south" (all numbers). Write one call that draws two overlapping, semi-transparent area charts with the quarters on the x axis.
Show answer
df.set_index("quarter").plot.area(stacked=False, alpha=0.4). Moving "quarter" into the index puts it on the x axis, stacked=False makes the areas overlap, and alpha makes them transparent.
Exercise
Why can a stacked area chart mislead when one column contains negative values?
Show answer
Negative values are stacked below zero, so the top edge of the chart no longer equals the sum of the columns. Readers will misjudge the totals.