Sub topic 3
Picking a chart type with kind and df.plot.<kind>
This chapter assumes you can build a DataFrame, select columns, and have pandas and matplotlib installed. You should also know that df.plot() draws one line per numeric column, using the index as the x axis.
Two ways to choose a chart
The default chart is a line chart. To get something else, you have two equivalent options:
- Pass the
kindargument:df.plot(kind="bar"). - Call an accessor method:
df.plot.bar().
df.plot is both a callable and an object that holds one method per chart type. Both forms run the same code and accept the same keyword arguments. The accessor form is easier to autocomplete in an editor and shows which options a chart type supports. The kind form is handy when the chart type is stored in a variable.
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],
})
data = df.set_index("month")
chart_type = "bar"
data.plot(kind=chart_type, rot=0) # kind form
data.plot.bar(rot=0) # accessor form, same chart
plt.show()Available chart types
| kind | Accessor | Typical use |
|---|---|---|
| `"line"` | `df.plot.line()` | Trends over an ordered index |
| `"bar"` | `df.plot.bar()` | Compare categories |
| `"barh"` | `df.plot.barh()` | Same, with horizontal bars |
| `"hist"` | `df.plot.hist()` | Distribution of one variable |
| `"box"` | `df.plot.box()` | Spread and outliers |
| `"kde"` or `"density"` | `df.plot.kde()` | Smoothed distribution |
| `"area"` | `df.plot.area()` | Stacked trends |
| `"pie"` | `df.plot.pie()` | Shares of a whole |
| `"scatter"` | `df.plot.scatter()` | Relationship between two columns |
Some types need extra arguments. scatter requires both x and y. pie needs a single column, so you pass y="sales" or plot a Series. Later chapters cover these in detail.
Chart types change how data is read
The chart type decides how pandas reads your DataFrame. A line chart, bar chart, or area chart treats the index as the categories or positions on the x axis, and each column becomes a series. A histogram or box plot ignores the index and looks only at the values in each column.
The diagram shows the decision.
Extra arguments depend on the kind
Each kind accepts its own options in addition to the shared ones such as title and figsize. For example, bins works for hist but not for line.
import numpy as np
rng = np.random.default_rng(0)
scores = pd.DataFrame({
"math": rng.normal(70, 10, 500),
"art": rng.normal(65, 15, 500),
})
scores.plot.hist(bins=20, alpha=0.5)
scores.plot.box()
plt.show()Here alpha=0.5 makes the bars transparent so the two histograms stay visible where they overlap. The box plot draws one box per column, side by side.
Common mistakes
- A misspelled kind.
kind="bars"raises aValueErrorthat lists the valid names. - Missing required arguments. Calling
df.plot.scatter()withoutxandyraises an error. - Using a text column as data. Columns like
monthare not numeric. Move them to the index withset_index, or pandas raisesTypeError: no numeric data to plot.
Exercise
You have a DataFrame df with a numeric column price. Write two different calls that draw a histogram of price with 10 bins.
Show answer
df["price"].plot(kind="hist", bins=10) and df["price"].plot.hist(bins=10). Both produce the same chart, because df.plot.hist is the accessor for kind="hist".
Exercise
Why does df.plot.bar() fail with "no numeric data to plot" on a DataFrame whose only columns are city and country, both strings?
Show answer
Plotting needs numeric columns to draw. Text columns can serve as the index, but there are no values left to draw, so you need at least one numeric column.