Sub topic 1
Your first chart: calling plot on a DataFrame
DataFrame.plot turns a table into a chart with one call. This chapter covers what that call does by default, how it chooses what to draw, and the first errors you are likely to hit. Later chapters cover chart types, styling, and finer control.
Prerequisites
This chapter assumes you can:
- Write basic Python: imports, dictionaries, method calls, keyword arguments.
- Create a DataFrame from a dictionary and select columns with
df["col"]ordf[["a", "b"]]. - Use
groupbyat a basic level. It appears only briefly here. - Run Python with pandas and matplotlib installed. Install them with
pip install pandas matplotlib.
pandas does not draw anything itself. DataFrame.plot hands the data to matplotlib, the default plotting backend. Without matplotlib installed, the call fails with an ImportError.
What plot does
df.plot() with no arguments draws a line chart. It follows two rules:
- The index becomes the x axis.
- Each numeric column becomes one line, and the column name becomes the legend label.
Here is a small sales table.
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.set_index("month").plot(marker="o")
plt.show()set_index("month") moves the month column into the index. After that, the DataFrame holds only numeric columns, sales and costs. plot draws two lines, with Jan to Apr on the x axis. marker="o" puts a dot at each data point. This is useful when there are few points, because you can see where the real values are.
plt.show() opens the figure window in a script. In Jupyter or other notebooks the chart usually appears automatically, but calling plt.show() does no harm.
The next diagram shows how plot maps the table onto the chart.
What happens without set_index
If you skip set_index, the index is the default RangeIndex: 0, 1, 2, 3. The string column month is not numeric, so plot leaves it out.
df.plot()
plt.show()You still get lines for sales and costs, but the x axis reads 0 to 3 instead of month names. Nothing fails, so the chart can look right at a glance and still be unhelpful. When a chart has the wrong x axis, check the index first.
You can also pick the columns with x and y:
df.plot(x="month", y=["sales", "costs"], marker="o")
plt.show()This gives the same chart as the set_index version. The x argument takes a column name. The y argument takes one name or a list of names. The next chapter covers the trade-offs between the two styles.
The return value
plot returns a matplotlib Axes object. This is the drawing area that holds the lines, ticks, and labels.
ax = df.set_index("month").plot(marker="o")
print(type(ax))
ax.set_ylabel("Units")
plt.show()The output of print(type(ax)) is <class 'matplotlib.axes._axes.Axes'>. Keep the object whenever you want to add labels, adjust limits, or save the figure. A later chapter treats it in detail. In a notebook, ending a cell with df.plot() also displays the repr of the returned Axes, which looks like <Axes: >. Assign the result to a variable, or end the line with a semicolon, to suppress that text.
Series.plot works the same way
A single column is a Series, and Series.plot follows the same rule with one line:
df.set_index("month")["sales"].plot(marker="o", title="Sales")
plt.show()The Series index becomes the x axis and the values become the y axis. For a Series, the line is labeled with the Series name only if you ask for a legend, because a single line has no need for one by default.
How the x axis treats strings
A string index such as month names is treated as categories. matplotlib places them at equal spacing and labels each tick with the string. It does not know that "Jan" comes before "Feb". The order is whatever order the rows have. If the rows are shuffled, the line zigzags across the chart in that order.
A numeric index is treated as real numbers. Unsorted numeric values draw a line that jumps back and forth, because plot connects points in row order and never sorts them. When a line looks tangled, call df.sort_index() before plotting.
shuffled = pd.DataFrame(
{"value": [3, 1, 2, 4]},
index=[3, 1, 2, 4],
)
shuffled.sort_index().plot(marker="o")
plt.show()Missing values
A NaN value is not drawn. In a line chart, it leaves a gap in the line.
import numpy as np
gappy = pd.DataFrame(
{"reading": [1.0, 2.0, np.nan, 4.0, 5.0]},
)
gappy.plot(marker="o")
plt.show()The chart shows a line from points 0 to 1, a break at index 2, and a line from 3 to 4. Where a point sits between NaN values on both sides, it shows only as an isolated marker, and without marker it is invisible. If you want a continuous line, fill the gaps first, for example with gappy.interpolate(). Decide deliberately whether to fill. A gap is honest about missing data, and an interpolated line hides it.
Errors you will see first
The most common first error comes from a DataFrame with no numeric columns.
text_only = pd.DataFrame({"city": ["Oslo", "Rome"], "country": ["NO", "IT"]})
try:
text_only.plot()
except TypeError as err:
print(err)This prints no numeric data to plot. plot found nothing to turn into lines. The same message often appears when numbers were loaded as strings, for example from a CSV with a thousands separator like "1,200". Check df.dtypes. If a column that should be numeric shows object, convert it:
df["sales"] = pd.to_numeric(df["sales"], errors="coerce")With errors="coerce", values that cannot be parsed become NaN instead of raising an error. That avoids a crash, but you then need to check how many values were lost.
The second common problem is a chart that does not appear. In a plain script, you must call plt.show() or save the figure. In a notebook, an inline backend may not be active. The %matplotlib inline magic command turns it on.
The third is an empty chart on a headless server, where there is no display. Matplotlib then needs a non-interactive backend, which you choose with matplotlib.use("Agg") before importing pyplot. You then save the figure to a file instead of showing it.
A short workflow
A reliable routine for a first chart:
- Look at
df.dtypesanddf.head(). - Decide which column should be the x axis, and call
set_indexon it, or passx=. - Select only the columns you want to compare. A column with values in the thousands next to one with values near 1 flattens the smaller one.
- Call
plot, keep the returnedAxes, and look at the result before styling.
ax = (
df.set_index("month")[["sales", "costs"]]
.plot(marker="o", title="Sales and costs, Jan to Apr")
)
ax.set_ylabel("Units")
plt.show()Selecting [["sales", "costs"]] with double brackets keeps a DataFrame, so both lines are drawn. A single bracket pair would give a Series with one line.
Exercise
You run df.plot() on a DataFrame with a text column day (values "Mon", "Tue", "Wed") and a numeric column visits. The chart shows one line with the x axis labeled 0, 1, 2. What happened, and what one change puts the day names on the x axis?
Show answer
The default RangeIndex (0, 1, 2) was used as the x axis, and the text column day was skipped because it is not numeric. Move day into the index with df.set_index("day").plot(), or call df.plot(x="day", y="visits").
Exercise
A DataFrame has a numeric column price stored as strings like "1,200" (dtype object). df.plot() raises TypeError: no numeric data to plot. How do you fix it, and what does errors="coerce" do in your fix?
Show answer
Convert the column to numbers first, for example after removing the commas: df["price"] = pd.to_numeric(df["price"].str.replace(",", ""), errors="coerce"). With errors="coerce", values that cannot be parsed become NaN instead of raising an error, so you should count the NaN values afterward to see how many were lost.