Sub topic 2
What goes on the x and y axes: the index, x and y
This chapter explains how DataFrame.plot decides what to draw on each axis. It assumes you can build a DataFrame, select columns, and run matplotlib in your environment. The behavior here applies to the default line chart and carries over to most other chart types. Scatter and pie plots add rules of their own, which later chapters cover.
The default rule: index on x, columns on y
Called with no arguments, plot uses two rules:
- The index supplies the x values.
- Each numeric column becomes one series on the y axis, drawn as its own line with its own legend entry.
Here is a small table to work with.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({
"month": ["Jan", "Feb", "Mar", "Apr"],
"sales": [120, 135, 150, 170],
"costs": [80, 90, 95, 110],
})
df.plot()
plt.show()The index of df is a RangeIndex with the values 0, 1, 2, 3. The chart therefore has x positions 0 to 3, and two lines for sales and costs. The month column is text, so plot skips it without warning. The result is a valid chart, but the x axis shows row numbers instead of month names, which is rarely what you want.
Option 1: move the labels into the index
If a column holds the labels you want on the x axis, make it the index with set_index. The default rule then does the right thing.
df.set_index("month").plot(marker="o")
plt.show()set_index returns a new DataFrame, so df itself is unchanged. The chart now has one line per numeric column, and the x axis shows Jan to Apr. The marker="o" argument draws a dot at each data point, which helps when there are only a few points.
You can also select columns before plotting. This is a good way to control exactly what appears:
df.set_index("month")[["sales"]].plot()
plt.show()The double brackets keep the result a DataFrame. Single brackets give a Series, which plot handles the same way. A Series has no columns, so its index is x and its values are y.
Option 2: name the columns with x and y
Instead of changing the index, you can tell plot which columns to use.
df.plot(x="month", y="sales")
plt.show()This draws one line of sales against month. Both arguments take column names.
y also accepts a list, so you can plot several columns against the same x:
df.plot(x="month", y=["sales", "costs"], marker="o")
plt.show()If you give x and leave out y, plot draws all remaining numeric columns and excludes the x column itself:
df.plot(x="month")
plt.show()This gives the same chart as the previous call. For a two-column plot of sales and costs, the two forms are interchangeable.
Comparing the two approaches
| Approach | Code | Where x comes from | Good when |
|---|---|---|---|
| Index | `df.set_index("month").plot()` | The index | You want to plot all or most columns against one label column, or the index is already meaningful (dates, IDs). |
| `x` and `y` | `df.plot(x="month", y="sales")` | The `x` column | You want to pick one or a few columns without changing the DataFrame. |
Both approaches produce the same picture. The main practical difference is that x= leaves the DataFrame untouched, while set_index gives you a new object you can chain further operations on.
Checking what plot will use
Before you plot, it helps to see what the default rule will find. Two quick checks cover most cases:
print(df.index)
print(df.select_dtypes("number").columns.tolist())The first line shows what will be on the x axis. The second lists the columns that will be drawn when you leave out y. For the example table, the index is a RangeIndex and the numeric columns are ['sales', 'costs'].
Pitfall: numbers that are really labels
plot decides by data type, not by meaning. A column of years is numeric, so it becomes a line:
yearly = pd.DataFrame({
"year": [2021, 2022, 2023, 2024],
"revenue": [1.2, 1.5, 1.9, 2.4],
})
yearly.plot() # draws two lines: year and revenue
plt.show()The year line climbs from 2021 to 2024 and squashes the revenue line flat near zero. The fix is to name year as the x axis, which takes it out of the plotted series:
yearly.plot(x="year", y="revenue", marker="o")
plt.show()The same trap applies to ID columns, zip codes, and any integer code. If a number is a label, put it in x or in the index.
Pitfall: no numeric data
If no numeric columns are left to plot, pandas raises an error:
text_only = pd.DataFrame({"city": ["Oslo", "Rome"], "country": ["NO", "IT"]})
text_only.plot()TypeError: no numeric data to plotThis happens in several ways:
- The DataFrame has only text columns, as above.
- Numbers were read as strings, for example from a CSV with a thousands separator, so they have the
objectdtype. - You moved the only numeric column into the index with
set_index.
For the second case, check df.dtypes and convert with pd.to_numeric(df["col"], errors="coerce"). The errors="coerce" option turns unparseable values into NaN, so you will see gaps in the line instead of a crash. The third case needs you to keep at least one numeric column outside the index.
Also note that if y names a text column, you get an error for that column even when other columns are numeric. The silent skipping only applies when y is left out.
Pitfall: x with a text column on a line chart
When x is a text column, pandas treats the values as categories. It places them at positions 0, 1, 2, and so on, and uses the strings as tick labels. This works for month. The order on the axis is the row order, not alphabetical. If your data is not sorted the way you want, sort it first:
df.sort_values("sales").plot(x="month", y="sales")
plt.show()For a numeric or datetime x, pandas places points at their true positions. Unsorted rows then draw a line that jumps back and forth. Sort by the x column with sort_values or sort_index before plotting.
Summary of rules
- No arguments: x is the index, and each numeric column is a series.
x="col": that column is x, and the remaining numeric columns are series.y="col"ory=[...]: only those columns are plotted.- Numeric label columns such as years must go in
xor the index, or they are drawn as data. - With no numeric columns left, pandas raises
TypeError: no numeric data to plot.
Exercise
A DataFrame has the columns "year" (integers 2020 to 2024), "visits" and "signups" (both numbers), and a default RangeIndex. You call df.plot() and get three lines, with the year line dominating the chart. Write two different calls that plot only visits and signups against year, and say what each one does to the DataFrame.
Show answer
Call 1: df.plot(x="year", y=["visits", "signups"]). It names year as the x axis and plots the two columns, and it leaves df unchanged. Call 2: df.setindex("year").plot(). It moves year into the index of a new DataFrame, so the default rule uses the index as x and plots the two remaining numeric columns. df itself is unchanged, because setindex returns a new object. Both calls draw the same chart.