Sub topic 4
Line and area charts
This chapter assumes you can build a DataFrame, select columns, and run a script or notebook with matplotlib installed. You should also know from the previous chapters that df.plot() puts the index on the x axis and draws one series per numeric column.
Line charts: the default
Calling plot without kind draws a line chart. kind="line", df.plot.line() and plain df.plot() are equivalent. The line chart suits ordered data, where the position along the x axis means something: time, a step number, a distance.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"sales": [120, 135, 150, 170, 160, 185],
"costs": [80, 90, 95, 110, 105, 115],
})
ax = df.set_index("month").plot.line(
style=["o-", "s--"],
title="Sales and costs",
figsize=(7, 4),
)
ax.set_ylabel("Thousands of dollars")
plt.show()Here set_index("month") moves the labels to the index, so they become the x ticks. Without it, month is a string column, pandas skips it, and the x axis shows the integers 0 to 5.
Styling the lines
The style argument takes matplotlib format strings. Each string combines a marker, a line style and optionally a color. For example, "o-" is circles joined by a solid line, "s--" is squares with a dashed line, and "g:" is a green dotted line. Pass a list to style columns in order, or a dict to style columns by name.
Keyword arguments that are not pandas options go through to matplotlib.axes.Axes.plot. That is why marker="o", linewidth=2, linestyle="--" and alpha=0.7 work directly. Keywords apply to every line. If you need different settings per line, use style with a dict or a list.
| Argument | Effect | Example |
|---|---|---|
| `style` | Format string per line, as a list or dict | `style={"sales": "o-", "costs": "s--"}` |
| `marker` | Marker for every line | `marker="o"` |
| `linewidth` | Line thickness for every line | `linewidth=2` |
| `logy` | Logarithmic y axis | `logy=True` |
| `secondary_y` | Column(s) drawn against a right-hand axis | `secondary_y="costs"` |
Two scales on one chart
Series with very different magnitudes squash each other. A common fix is to draw one column against a second y axis on the right.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"revenue": [120000, 135000, 150000, 170000, 160000, 185000],
"margin_pct": [33.0, 33.3, 36.7, 35.3, 34.4, 37.8],
}).set_index("month")
ax = df.plot(secondary_y="margin_pct", marker="o", figsize=(7, 4))
ax.set_ylabel("Revenue")
ax.right_ax.set_ylabel("Margin (%)")
plt.show()The returned ax is the left axis. pandas attaches the right axis as ax.right_ax. Use it for labels and limits on the secondary scale. Two scales can mislead readers, because the visual crossing point of two lines is arbitrary. Use this only when the two series are clearly labeled and a shared axis would hide one of them.
How a line chart reads your rows
A line chart connects points in row order. It does not sort them by x value. If your index is unsorted, the line zigzags back and forth across the chart.
import pandas as pd
import matplotlib.pyplot as plt
shuffled = pd.DataFrame(
{"y": [1, 4, 9, 16, 25]},
index=[3, 1, 5, 2, 4],
)
shuffled.sort_index().plot(marker="o", title="Sorted before plotting")
plt.show()Remove .sort_index() and the line jumps between points in the order 3, 1, 5, 2, 4. Sorting first is the fix. The same applies to a datetime index, which later chapters cover.
Missing values
A NaN in a line chart breaks the line. The points on each side of the gap are not connected. A single isolated point between two gaps has no line at all and is invisible unless you set a marker.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
s = pd.Series([1.0, 2.0, np.nan, 4.0, 5.0], name="reading")
fig, axes = plt.subplots(1, 2, figsize=(8, 3), sharey=True)
s.plot(ax=axes[0], marker="o", title="Gap kept")
s.interpolate().plot(ax=axes[1], marker="o", title="Interpolated")
plt.tight_layout()
plt.show()Keeping the gap is usually the honest choice, since it shows that data is missing. Use interpolate() or ffill() only when you know the filled values are reasonable, and say so in the chart or caption. The ax= argument used above is covered in the chapter on the returned Axes.
Area charts
An area chart is a line chart with the region under each line filled in. Use kind="area" or df.plot.area(). Two things differ from a line chart:
- Area charts are stacked by default, so each series sits on top of the previous one. The top edge shows the total.
- Area charts replace
NaNwith0before drawing, so gaps become drops to zero rather than breaks in the line.
import pandas as pd
import matplotlib.pyplot as plt
traffic = pd.DataFrame({
"week": [1, 2, 3, 4, 5, 6],
"search": [300, 320, 350, 340, 380, 400],
"social": [120, 150, 140, 180, 200, 210],
"direct": [200, 190, 210, 205, 215, 220],
}).set_index("week")
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), sharey=True)
traffic.plot.area(ax=axes[0], title="Stacked (default)")
traffic.plot.area(ax=axes[1], stacked=False, alpha=0.4, title="Overlaid")
plt.tight_layout()
plt.show()The left panel answers "how big is the total, and how is it split?" The right panel answers "how does each series compare to the others?" It needs alpha below 1, otherwise the front series hides the ones behind it. In the overlaid version the fill order follows the column order, so a large series listed last covers the others. Reorder the columns if that happens.
Choosing between line and area
Edge cases and common errors
- Mixed signs in one column. A stacked area chart raises a
ValueErrorwhen a single column contains both positive and negative values. Different columns may differ in sign, because pandas stacks positives and negatives separately. If one series changes sign, use a line chart orstacked=False. - Stacked areas hide the middle series' trend. Only the bottom series sits on a flat baseline. Every other series rides on the ones below it, so its shape is hard to read. When individual trends matter more than the total, use lines.
- Too many lines. More than about six lines become unreadable. Plot a subset, or use
subplots=True(a later chapter). - No numeric data. If every column is text, pandas raises
TypeError: no numeric data to plot. Convert withpd.to_numeric(..., errors="coerce")or choose numeric columns. - Dates stored as strings. A string index plots as evenly spaced categories, even if the real gaps between dates differ. Convert with
pd.to_datetimefirst. - Area with
NaN. BecauseNaNbecomes0, an area chart can show a false collapse. Fill or drop missing values on purpose before plotting.
Summary of the options
| Goal | Call |
|---|---|
| Basic line chart | `df.plot()` or `df.plot.line()` |
| Markers on each point | `df.plot(marker="o")` |
| Per-column line style | `df.plot(style={"a": "o-", "b": "s--"})` |
| Second y axis | `df.plot(secondary_y="col")` |
| Log scale | `df.plot(logy=True)` |
| Stacked area | `df.plot.area()` |
| Overlaid area | `df.plot.area(stacked=False, alpha=0.4)` |
Exercise
You call df.plot.area() on a DataFrame where one column has a few NaN values, and the chart shows sharp drops to the baseline. Explain why this happens, and give one line of code that avoids the drops by connecting the neighboring points instead.
Show answer
Area plots replace NaN with 0 before drawing, so each missing value becomes a point at zero and the filled region falls to the baseline there. Interpolating first fills in intermediate values, for example df.interpolate().plot.area(). Using df.ffill().plot.area() also works if you prefer to carry the last value forward.
Exercise
A line chart of df.plot(marker="o") zigzags across the chart even though the data is correct. The index holds the integers 1 to 10, but the rows are in a random order. What is the cause and the fix?
Show answer
A line chart connects points in row order, not in x order. Sort the rows by index before plotting: df.sort_index().plot(marker="o").