Sub topic 1
Quick Charts from a DataFrame with the pandas plot Method
Pandas plotting is a convenient interface to Matplotlib. Assume you know basic DataFrame selection and have pandas and Matplotlib installed.
Prerequisites
You should know how to create a DataFrame, select columns, and use groupby. You should also understand that Matplotlib displays or saves charts.
Your first chart: calling `plot` on a DataFrame
DataFrame.plot() creates a chart from the DataFrame. By default, it draws a line for each numeric column and uses the DataFrame index for the horizontal axis.
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()What goes on the x and y axes: the index, `x` and `y`
The index supplies x-axis values. Each selected numeric column supplies a y-axis series. Use x and y when the useful x values are still ordinary columns:
df.plot(x="month", y=["sales", "costs"], marker="o", rot=0)
plt.show()set_index("month") changes the DataFrame so that month becomes the index. It does not change the original DataFrame unless you assign the result or use inplace=True.
flowchart TD
A[DataFrame] --> B[Index values]
A --> C[Numeric columns]
B --> D[X axis]
C --> E[Y series]
F[x and y arguments] --> D
F --> EPicking a chart type with `kind` and `df.plot.<kind>`
The kind argument selects the chart type. The accessor form, such as df.plot.bar(), is equivalent and often easier to read.
df.plot(x="month", y="sales", kind="bar", rot=0)
plt.show()
df.set_index("month")[["sales", "costs"]].plot.bar(stacked=True, rot=0)
plt.show()Common values include line, bar, barh, area, hist, box, kde, pie, and scatter. The required columns depend on the chart. For example, a scatter plot needs numeric x and y columns.
Line and area charts
Line charts show change across an ordered index, such as months. Area charts fill the space below one or more lines, which can emphasize totals or composition. Use area charts only when stacking or overlap will not hide important values.
monthly = df.set_index("month")
monthly[["sales", "costs"]].plot(
kind="area",
alpha=0.5,
title="Monthly sales and costs",
)
plt.ylabel("Units")
plt.show()Exercise
What does pandas use for the x axis when you call df.plot() without x?
Show answer
It uses the DataFrame index.