Sub topic 13
Common errors: non-numeric columns, missing data and overlapping labels
This chapter assumes you can build a DataFrame, select columns, and call df.plot() with kind, x, y and set_index. It also assumes you know that plot returns a matplotlib Axes. Most plotting failures fall into three groups: pandas finds no numbers to draw, the data has gaps, or the labels collide. Each group is easy to fix once you know what pandas does internally.
Non-numeric columns
DataFrame.plot draws only numeric columns for line, bar, area, histogram and box charts. Other columns are dropped without a warning. If no numeric column is left, pandas raises:
TypeError: no numeric data to plotThe cause is usually a column of dtype object. Typical culprits are numbers stored as text, such as "1,200", "$15", "12%" or "n/a". Check df.dtypes before you blame the plot call.
import pandas as pd
import matplotlib.pyplot as plt
raw = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"revenue": ["1,200", "1,350", "n/a", "1,700"],
})
print(raw.dtypes)
try:
raw.set_index("month").plot()
except TypeError as err:
print("Error:", err)
plt.close("all")
clean = raw.assign(
revenue=pd.to_numeric(
raw["revenue"].str.replace(",", "", regex=False),
errors="coerce",
)
)
print(clean.dtypes)
clean.set_index("month").plot(marker="o")
plt.show()The first plot fails because revenue holds strings. After cleaning, revenue is float64. The errors="coerce" argument turns anything that cannot be parsed, here "n/a", into NaN. That choice trades a loud error for a quiet gap, which leads to the next section.
An empty DataFrame also raises this error. If a filter such as df[df["year"] == 2030] matches nothing, the plot reports "no numeric data" even though the dtypes are fine. Print df.shape when the dtypes look correct.
Numbers that are plotted when they should be the axis
The opposite mistake is a numeric column that you meant as the x axis. A year column with values like 2021 and 2022 is numeric, so df.plot() draws it as a line against the row numbers. Move it to the index or name it in x:
yearly = pd.DataFrame({
"year": [2021, 2022, 2023],
"users": [100, 140, 200],
})
yearly.plot() # wrong: draws year as a data line
yearly.plot(x="year", y="users") # right
yearly.set_index("year").plot() # also right
plt.show()Other argument errors
- A misspelled name in
xoryraisesKeyError. Names are case sensitive. kind="scatter"needs bothxandy. Without them pandas raises aValueError.- A non-numeric column named in
yfails in the same way as a whole frame of strings.
Missing data
How NaN is treated depends on the chart type. This is the part most likely to give you a misleading chart without any error.
| Chart type | What pandas does with `NaN` |
|---|---|
| Line | Leaves a gap. The line is broken at that point. |
| Stacked line and area | Replaces `NaN` with 0, so the area falls to zero. |
| Bar | Draws no bar for that value. |
| Histogram and box | Drops the `NaN` values separately for each column. |
| Scatter | Skips any point where x or y is `NaN`. |
Two details matter in practice. First, a single valid point between two NaN values has no neighbors to connect to, so a line chart without markers shows nothing for it. Use marker="o" to keep isolated points visible. Second, because area charts fill with 0, they can suggest a collapse that never happened.
You choose how to handle gaps before plotting. The three usual options are to keep the gap, interpolate, or fill with a constant:
s = clean.set_index("month")["revenue"]
fig, axes = plt.subplots(1, 3, figsize=(10, 3), sharey=True)
s.plot(ax=axes[0], marker="o", title="Gap (default)")
s.interpolate().plot(ax=axes[1], marker="o", title="interpolate")
s.fillna(0).plot(ax=axes[2], marker="o", title="fillna(0)")
plt.tight_layout()
plt.show()interpolate() draws a straight line through the missing month, which suggests data that was never measured. fillna(0) is correct only if zero is the true value, such as "no sales". The gap is the most honest choice when the value is unknown. Use dropna() when you want to remove incomplete rows, for example before a scatter plot where you want to count the points.
Also compare the counts when you use histograms. A histogram of 500 rows may be drawn from 430 values if 70 are missing. Run df.isna().sum() to see how much is being dropped.
Overlapping labels
When there are many categories or long names, the tick labels on the x axis collide. pandas rotates category labels to 90 degrees for bar charts by default, which is readable but tall. Other charts keep them horizontal. These fixes are listed from simplest to most flexible:
- Switch to horizontal bars with
plot.barh. Long names then read left to right on the y axis. - Increase
figsizeto give each label more space. - Rotate labels with
rot=45and right-align them so they end under their tick. - Reduce the number of categories, for example with
sort_values().tail(10). - Call
plt.tight_layout()or save withbbox_inches="tight"so nothing is cut off.
import numpy as np
rng = np.random.default_rng(1)
cities = [f"City number {i}" for i in range(1, 16)]
pop = pd.Series(rng.integers(100, 900, len(cities)), index=cities)
ax = pop.plot.bar(figsize=(8, 4), rot=45)
plt.setp(ax.get_xticklabels(), ha="right", rotation_mode="anchor")
ax.set_ylabel("Population (thousands)")
plt.tight_layout()
plt.show()
pop.sort_values().tail(8).plot.barh(figsize=(6, 3.5))
plt.tight_layout()
plt.show()The first chart rotates all 15 labels, and ha="right" with rotation_mode="anchor" makes each label end at its tick. The second keeps the eight largest cities in a horizontal chart, which is often the better design.
For a datetime index, matplotlib can rotate and format the dates for you:
ts = pd.Series(
rng.normal(size=60).cumsum(),
index=pd.date_range("2026-01-01", periods=60, freq="D"),
)
ax = ts.plot()
ax.figure.autofmt_xdate()
plt.show()A legend can also cover the data. Move it outside the plot area and keep it from being clipped when you save:
ax = df_wide = pd.DataFrame(
rng.random((5, 3)), columns=["alpha", "beta", "gamma"]
).plot()
ax.legend(loc="upper left", bbox_to_anchor=(1.02, 1))
ax.figure.savefig("legend_outside.png", bbox_inches="tight")Without bbox_inches="tight", the saved file would crop the legend, because the figure boundary does not include artists placed outside the axes.
A quick diagnostic path
The diagram summarizes the order in which to check a chart that fails or looks wrong.
Summary of symptoms and fixes
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: no numeric data to plot` | Text columns or an empty frame | Check `dtypes` and `shape`, convert with `to_numeric` |
| A column is missing from the chart | The column is `object` dtype | Convert it, or select numeric columns explicitly |
| A `year` column appears as a line | Numeric column left as data | Use `x="year"` or `set_index("year")` |
| Line is broken or a point is invisible | `NaN` values | Add `marker="o"`, then interpolate, fill or accept the gap |
| Area chart drops to zero | `NaN` filled with 0 | Clean the data before plotting |
| `KeyError` in `x` or `y` | Misspelled column name | Compare with `df.columns` |
| Tick labels overlap | Too many or too long labels | `barh`, `rot`, `figsize`, `tight_layout` |
| Legend cut off in the saved file | Legend outside the axes | `bbox_inches="tight"` in `savefig` |
Exercise
A DataFrame has columns "city" (strings) and "population" (strings such as "1,250,000"). Calling df.set_index("city").plot.bar() raises "TypeError: no numeric data to plot". Write the code that fixes it and draws a horizontal bar chart. Explain what happens to a value that cannot be parsed.
Show answer
Remove the commas and convert to numbers, then plot with barh: df["population"] = pd.tonumeric(df["population"].str.replace(",", "", regex=False), errors="coerce") df.setindex("city")["population"].sortvalues().plot.barh() With errors="coerce", a value that cannot be parsed becomes NaN. In a bar chart, that city gets no bar. sortvalues places NaN last, so the missing city sits at the end, and df["population"].isna().sum() tells you how many values were lost.
Exercise
A line chart of daily temperatures has a gap on one day because the sensor was offline. Name two ways to remove the gap and say which one could mislead readers.
Show answer
Use s.interpolate() to draw a straight line across the day, or s.fillna(value) to insert a constant. fillna(0) is the more misleading one, because it draws a drop to 0 degrees that never happened. Interpolation also invents a value, so the gap is the most honest option when the reading is truly unknown.
Exercise
You save a chart with ax.figure.savefig("out.png") and the legend, which you placed outside the axes with bboxtoanchor, is cut off. What argument fixes this?
Show answer
Pass bboxinches="tight", as in ax.figure.savefig("out.png", bboxinches="tight"). It enlarges the saved area to include artists that sit outside the axes.