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 and y. Most plot failures come from three causes: columns that are not numeric, missing values, and crowded tick labels. Each is quick to diagnose once you know what to look for.
Error 1: no numeric data to plot
DataFrame.plot draws numeric columns only. If every column holds text, pandas raises TypeError: no numeric data to plot. This often happens when numbers were read from a CSV as strings, for example "1,200" or "$15".
import pandas as pd
import matplotlib.pyplot as plt
raw = pd.DataFrame({
"month": ["Jan", "Feb", "Mar"],
"sales": ["1,200", "1,350", "1,500"],
})
print(raw.dtypes)
try:
raw.set_index("month").plot()
except TypeError as err:
print("Error:", err)
raw["sales"] = pd.to_numeric(raw["sales"].str.replace(",", ""), errors="coerce")
raw.set_index("month").plot(marker="o")
plt.show()The object dtype in the output is the clue. pd.to_numeric converts the strings, and errors="coerce" turns anything it cannot parse into NaN instead of raising an error. Check how many values became NaN afterwards, because coercion hides bad input.
A related mistake is a text column left among the data columns. A column such as month is silently skipped when other numeric columns exist. If your x labels are missing, move that column into the index with set_index or pass it as x.
Error 2: missing data
Missing values (NaN) are not drawn. What happens next depends on the chart type.
| Chart | Effect of NaN |
|---|---|
| Line | A gap appears at the missing point |
| Bar | The bar is missing |
| Area | Treated as 0 by default |
| Histogram, box | Dropped before the statistics are computed |
import numpy as np
gaps = pd.DataFrame(
{"temp": [14.0, 15.5, np.nan, np.nan, 18.0, 19.5]},
index=pd.date_range("2026-01-01", periods=6, freq="D"),
)
fig, axes = plt.subplots(1, 3, figsize=(11, 3))
gaps.plot(marker="o", title="Gap", ax=axes[0])
gaps.interpolate().plot(marker="o", title="Interpolated", ax=axes[1])
gaps.fillna(0).plot(marker="o", title="Filled with 0", ax=axes[2])
plt.tight_layout()
plt.show()Choose the treatment deliberately. A gap is honest. interpolate() draws a straight line between known points, which suggests data you do not have. fillna(0) is only correct if zero is the true value, and otherwise it adds a false drop to the chart.
A line chart also breaks into isolated dots when a point has NaN on both sides. Without marker="o" those points can seem to vanish.
Error 3: overlapping labels
Long category names or many dates make the x tick labels collide. Three fixes cover most cases.
cities = pd.DataFrame({
"city": ["San Francisco", "Los Angeles", "San Diego", "Sacramento", "Fresno", "Oakland"],
"population": [815, 3898, 1386, 525, 542, 440],
})
cities.plot.bar(x="city", y="population", rot=45, legend=False)
plt.tight_layout()
plt.show()
cities.plot.barh(x="city", y="population", legend=False)
plt.tight_layout()
plt.show()- Rotate the labels with
rot=45. Addha="right"throughplt.setp(ax.get_xticklabels(), ha="right")if rotated labels sit off-center. - Use
barhso long names are read horizontally. - Call
plt.tight_layout()or save withbbox_inches="tight"so labels are not cut off at the figure edge.
If there are still too many categories, plot fewer. Sort and keep the top ten with nlargest(10).
Exercise
A DataFrame has the columns day (text), visits (numbers stored as strings like "1,050") and signups (floats with some NaN). df.set_index("day").plot() raises "no numeric data to plot". What two steps fix it, and how will signups appear in the line chart?
Show answer
Convert visits with pd.to_numeric(df["visits"].str.replace(",", ""), errors="coerce"). Then visits is numeric, and it plots. (signups is already numeric, so the error occurs only when no column is numeric.) The NaN values in signups appear as gaps in the line. Use marker="o" so isolated points between gaps remain visible.
Exercise
You plot a bar chart of 30 product names and the labels overlap. Name three changes that make it readable.
Show answer
Use rot to rotate the labels, switch to barh so names are horizontal, or reduce the data with nlargest(10). Call plt.tight_layout() so nothing is clipped.