Sub topic 3
Picking a chart type with kind and df.plot.<kind>
This chapter assumes you can build a DataFrame, select columns, and call plot on it. You should also have matplotlib installed. The previous chapter covered how the index and the x and y arguments map onto the axes. Here you choose what kind of chart is drawn from those axes.
Two ways to ask for the same chart
DataFrame.plot draws a line chart by default. To get something else, pass the kind argument with the chart's name. The same chart is also available as a method on the plot accessor, written df.plot.<kind>().
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")
data.plot(kind="bar", rot=0)
data.plot.bar(rot=0)
plt.show()Both calls draw the same figure. The accessor form is shorter to read and your editor can autocomplete it. The kind form is easier when the chart type is stored in a variable, for example when a function receives it as a parameter.
def quick_chart(frame, chart_type):
return frame.plot(kind=chart_type)Both forms accept the same keyword arguments, so changing the chart type seldom means rewriting the rest of the call.
The available kinds
The kind argument accepts these values.
| kind | Accessor | Draws | Typical input |
|---|---|---|---|
| `"line"` | `df.plot.line()` | Lines connecting points (the default) | Ordered or time-based data |
| `"bar"` | `df.plot.bar()` | Vertical bars | Few categories in the index |
| `"barh"` | `df.plot.barh()` | Horizontal bars | Categories with long names |
| `"area"` | `df.plot.area()` | Filled areas under lines | Totals that change over time |
| `"hist"` | `df.plot.hist()` | Counts of values per bin | Numeric columns |
| `"box"` | `df.plot.box()` | Quartiles and outliers | Numeric columns |
| `"kde"` or `"density"` | `df.plot.kde()` | Smoothed density curve | Numeric columns |
| `"pie"` | `df.plot.pie()` | Slices of a whole | One column of positive parts |
| `"scatter"` | `df.plot.scatter()` | One point per row | Two numeric columns |
| `"hexbin"` | `df.plot.hexbin()` | Binned point density | Two numeric columns, many rows |
The kde and density names are aliases of each other. Drawing a density plot needs SciPy installed in addition to matplotlib.
Choosing by the shape of your question
Start from what you want the reader to see, then pick the kind.
The diagram below is the decision path to follow.
Which kinds use the index, and which use columns
The kinds fall into three groups, and knowing the group explains most surprises.
- Index on the x axis, one series per column. Line, area, bar and barh work this way. Each numeric column becomes one line or one set of bars. This is the behavior you saw in the previous chapter.
- One distribution per column. Hist, box and kde ignore the index. They look only at the values in each numeric column.
- Two named columns. Scatter and hexbin need
xandyas column names, because each row becomes one point. Pie works on a single series and uses the index as slice labels.
The distribution kinds are a good example of group 2.
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()The histogram overlays both columns, and alpha=0.5 makes the bars half transparent so the overlap stays visible. The box plot places the two columns side by side. The index here is just the numbers 0 to 499, and it never appears in either chart.
Arguments that depend on the kind
Many keyword arguments work for every kind, such as title, figsize, color, legend and rot. Others apply to one kind only. Passing an argument to a kind that does not use it either has no effect or raises an error, depending on the argument.
| Argument | Applies to | Effect |
|---|---|---|
| `stacked=True` | bar, barh, area, hist | Stacks series instead of placing them side by side or overlapping |
| `bins=20` | hist | Number of bins |
| `x`, `y` | line, bar, scatter, hexbin, and others | Selects columns for the axes |
| `c`, `s` | scatter | Color and size of the points |
| `autopct="%.0f%%"` | pie | Prints each slice's percentage |
| `subplots=True` | most kinds | One panel per column |
A scatter plot shows the difference clearly. It is the one common kind that fails without x and y.
trips = pd.DataFrame({
"distance": [1.2, 3.4, 5.1, 7.8, 10.5],
"fare": [6.0, 11.5, 16.0, 22.5, 30.0],
"passengers": [1, 2, 1, 3, 2],
})
trips.plot.scatter(x="distance", y="fare", s=trips["passengers"] * 40, c="passengers", colormap="viridis")
plt.show()Here s sets the marker size from the passengers column, and c colors each point by the same column. Scatter plots are covered in their own chapter, so treat this as a preview.
Pie charts need a Series or a chosen column
A pie chart shows one number per slice, so it cannot draw several columns at once. Pass a Series, or name the column with y.
shares = pd.DataFrame(
{"revenue": [50, 30, 20]},
index=["north", "south", "east"],
)
shares.plot.pie(y="revenue", autopct="%.0f%%", legend=False)
plt.ylabel("")
plt.show()Calling shares.plot.pie() without y raises an error when the DataFrame has more than one column. With a single column, pandas picks it for you only when you call the accessor on a Series, as in shares["revenue"].plot.pie(). Setting plt.ylabel("") removes the column name that pandas places on the y axis of a pie.
Kinds on a Series
A Series has the same plot method and the same accessors. Its values become the y values, and its index supplies the x values.
sales = df.set_index("month")["sales"]
sales.plot.bar(rot=0)
sales.plot.area()
plt.show()Two kinds exist only on a DataFrame because they need two columns: scatter and hexbin. Everything else works on both objects.
Common errors with kind
TypeError: no numeric data to plot. The columns you passed contain only text. Select numeric columns, convert withpd.to_numeric, or move the text column to the index withset_index.ValueError: scatter requires an 'x' and 'y' column to be specified. Add both arguments by name.ValueError: pie requires either y column or 'subplots=True'. Name the column withy, or plot a Series.- Misspelled kind. A value such as
kind="bars"raises aValueErrorthat lists the valid names. Compare your spelling against the table above. - Line chart where bars were intended. Forgetting
kindis not an error. You get the default line chart, which implies an order between categories that may not exist. If the x values are labels, use bars.
Mixing kinds on one chart
A single plot call draws one kind. To combine kinds, for example bars for sales and a line for a target, draw the first chart and pass the Axes it returns to the second call through ax.
combo = pd.DataFrame({
"sales": [120, 135, 150, 170],
"target": [130, 130, 160, 160],
}, index=["Jan", "Feb", "Mar", "Apr"])
ax = combo["sales"].plot.bar(rot=0, color="lightgray")
combo["target"].plot.line(ax=ax, color="crimson", marker="o")
plt.show()Bar charts place categories at positions 0, 1, 2 and so on, so a line drawn on the same Axes lines up with the bars. The ax argument is explained in detail in a later chapter.
for kind in ["line", "bar", "area"]:
df.set_index("month")[["sales", "costs"]].plot(kind=kind, title=kind)
plt.show()Exercises
Exercise
You have a DataFrame d with a text column city and numeric columns pop and area. You call d.plot.bar() and get "no numeric data" or a chart with meaningless x labels. What change fixes it so that each city gets a pair of bars?
Show answer
Move the text column to the index with d.set_index("city").plot.bar(). The index then supplies the category labels and the numeric columns pop and area become the two series of bars.
Exercise
Write one line that draws a pie chart of the column revenue in shares, showing whole-number percentages on the slices, and explain why shares.plot.pie() alone fails when shares has two columns.
Show answer
shares.plot.pie(y="revenue", autopct="%.0f%%"). A pie shows one value per slice, so pandas needs to know which single column to use. Without y and with several columns, it raises a ValueError asking for y or subplots=True.
Exercise
Which two kinds work with the index on the x axis but one of them stacks filled regions rather than bars? Name them and the argument that stacks the bars.
Show answer
bar and area. Both use the index for x. Area charts stack by default, and bar charts stack when you pass stacked=True.