skip to content

In pandas, what does DataFrame.plot draw by default, what does it return, and how do you pick another kind such as bar or hist?

level: juniorimportance: should knowfreq 50%

answer

  1. a thin layer over a plotting library
  2. index on x, one line per column
  3. kind= or the .plot accessor
  4. keep the return value to customise
  5. subplots=True changes the return type

basics

~10 s

By default DataFrame.plot draws one line per numeric column against the index, through Matplotlib, and returns the Matplotlib Axes it drew on. kind='bar', 'hist', 'box' or 'scatter', or df.plot.bar() and friends, picks another chart.

solid answer

~40 s

`df.plot()` is a thin wrapper over Matplotlib, the default `plotting.backend`. With no arguments it uses `kind="line"`: the index goes on the x axis and every numeric column becomes one line, while text columns are left out. `kind=` chooses among `line`, `bar`, `barh`, `hist`, `box`, `kde`/`density`, `area`, `pie`, `scatter` and `hexbin`, and the accessor form `df.plot.bar()` is the same call. `scatter` and `hexbin` work only on a DataFrame and need `x=` and `y=` columns. The return value is the Matplotlib `Axes` it drew on, so you keep it (`ax = df.plot(...)`) to set a title or labels, or pass `ax=ax` to a second call to draw on the same chart. With `subplots=True` you get a NumPy array of Axes instead, one per plotted column.

code

python · 21 lines
python
import pandas as pd

sales = pd.DataFrame(
    {
        "revenue": [120.0, 135.5, 128.0, 150.25],
        "orders": [40, 44, 41, 48],
        "region": ["N", "S", "N", "S"],
    },
    index=pd.date_range("2026-01-31", periods=4, freq="ME"),
)

ax = sales.plot(title="Monthly revenue and orders")  # kind="line"
print(type(ax).__name__)
print([line.get_label() for line in ax.get_lines()])
ax.set_ylabel("value")

axes = sales.plot(subplots=True)
print(type(axes).__name__, axes.shape)

ax2 = sales.plot(kind="scatter", x="orders", y="revenue")
print(type(ax2).__name__)

go deeper

for a junior

Recall that df.plot() draws lines against the index through Matplotlib, that kind= or df.plot.bar() picks another chart, and that it returns an Axes you can keep.

for a middle

Explain which columns pandas plots (numeric only, booleans opt-in), which kinds need x and y, and how subplots=True turns the return value into an array of Axes.

for a senior

Diagnose the common failures fast: a text revenue column behind 'no numeric data to plot', a scatter on a Series, a pie without y=, and a changed backend that returns non-Axes objects.

for a principal

There is no team decision hiding here beyond leaving plotting.backend at its default; the lead's job is making sure quick-look charts are not mistaken for reviewed reporting.

## What `DataFrame.plot` is pandas does not render charts itself. `DataFrame.plot` and `Series.plot` are a **plotting accessor**: they turn a frame's columns into calls on a **plotting backend**, and the default backend is **Matplotlib** (the option `plotting.backend` holds the string `"matplotlib"`). The accessor exists for speed, so that a quick look at a revenue series or a price distribution takes one line instead of a hand-built chart. With no arguments, `df.plot()` uses `kind="line"` and: - puts the **index** on the x axis (`use_index=True`), so a `DatetimeIndex` gives a dated axis; - draws **one line per numeric column**, with a legend labelled by column name; - leaves out columns it cannot plot: text columns are dropped, and boolean columns are dropped unless you pass `include_bool=True`; - raises `TypeError: no numeric data to plot` when no plottable column remains. ## Choosing a kind `kind=` selects the chart, and every kind also has an accessor method: `df.plot(kind="bar")` and `df.plot.bar()` are the same call. | `kind` | What it draws | Works on | |---|---|---| | `line` (default) | one line per column against the index | Series and DataFrame | | `bar`, `barh` | one bar per index label, grouped by column | Series and DataFrame | | `hist` | a histogram, 10 bins unless `bins=` says otherwise | Series and DataFrame | | `box` | one box per numeric column | Series and DataFrame | | `kde`, `density` | a smoothed density curve (needs SciPy installed) | Series and DataFrame | | `area` | stacked areas (`stacked=True` by default here) | Series and DataFrame | | `pie` | slices of one column | Series; a DataFrame needs `y=` or `subplots=True` | | `scatter` | points of `x` against `y` | DataFrame only, `x=` and `y=` required | | `hexbin` | hexagonal density of `x` against `y` | DataFrame only, `x=` and `y=` required | With the default backend, a kind outside this list raises `ValueError` with the list of valid kinds. Which chart answers which question is a design matter covered with chart choice in general; this call only decides how pandas draws it. ## What comes back The return value is the useful part of the call: - for one chart, a **`matplotlib.axes.Axes`**, the object every Matplotlib customisation hangs on (`ax.set_title`, `ax.set_ylabel`, `ax.axhline`); - with **`subplots=True`**, a **NumPy array of Axes**, one per plotted column; `layout=(rows, cols)` reshapes it into a grid; - with a **different backend**, whatever that backend returns, which is no longer an Axes. Because the Axes comes back, the usual pattern is to keep it: `ax = sales.plot(title="Revenue")`, then adjust it, or pass `ax=ax` to a second `.plot()` call so two frames share one chart. How Matplotlib's Figure and Axes objects fit together is covered with Matplotlib itself. ## Errors you will meet 1. `TypeError: no numeric data to plot`: the revenue column was imported as text such as `"1,200"` (dtype `str` or `object`). pandas does not parse it for you; clean and convert it first. 2. `ValueError: scatter requires an x and y column`: `df.plot(kind="scatter")` without `x=` and `y=`. 3. `ValueError: plot kind scatter can only be used for data frames`: `scatter` called on a Series. 4. `ValueError: pie requires either y column or 'subplots=True'`: a pie of a whole DataFrame. ## Common arguments that pass straight through Most quick-look tweaks do not need the Axes at all, because `DataFrame.plot` accepts them directly: - `title=` and `figsize=(width, height)` in inches; - `xlabel=` and `ylabel=`; by default the x label is the index name; - `logy=True` (or `logx`, `loglog`) for a log scale, useful for a price column with a long tail; - `secondary_y=["orders"]` to draw one column against a right-hand axis when its units differ; - `rot=` to rotate tick labels, `legend=False` to hide the legend; - `y="revenue"` (or a list of columns) to plot a subset, and `x="col"` to use a column instead of the index. Other keyword arguments are passed on to the Matplotlib plotting method, which is why `color=` and `linestyle=` work too. ## The `plotting.backend` option `pd.options.plotting.backend = "..."` (or `backend=` on one call) sends `.plot` to another package. The value must be `"matplotlib"`, a name that an installed package registers under the `pandas_plotting_backends` entry point, or an importable module with a top-level `plot` function; otherwise pandas raises `ValueError: Could not find plotting backend ...`. With another backend pandas hands the call over without checking `kind`, and returns that backend's object, so code that calls Axes methods on the result breaks. Few projects change it. ## Worked example A monthly revenue frame with a text `region` column: `sales.plot()` draws two lines (`revenue`, `orders`) and skips `region`; `sales.plot(subplots=True)` returns an array of two Axes.

  • How do you draw two DataFrames' revenue lines on the same pandas chart?
    Keep the Axes from the first call and pass it to the second: `ax = this_year.plot(y="revenue", label="2026")`, then `last_year.plot(y="revenue", ax=ax, label="2025")`. Without `ax=`, a DataFrame's `.plot()` opens a new figure, so the two lines land on separate charts.
  • What breaks if a project sets pd.options.plotting.backend to another package?
    Every `.plot` call is handed to that package, which must be installed and expose a top-level `plot`, or pandas raises `ValueError`. pandas stops validating `kind`, and the return value becomes that package's figure object, so any code that calls Matplotlib Axes methods such as `set_ylabel` on the result fails.
  • Why does a True/False column not appear in df.plot()?
    pandas filters the frame to plottable dtypes before drawing, and boolean columns are excluded by default. Pass `include_bool=True` to plot them as 0 and 1, or convert the column to an integer first.

  • df.plot returns a Matplotlib Figure, not an Axes
  • pandas draws charts with its own rendering engine
  • kind='scatter' works on a single Series
  • Text columns of numbers are parsed automatically before plotting
  • Nothing is returned, so pyplot calls are the only way to customise