Sub topic 2
Bar Charts, Distributions, and Scatter Plots
Assume you know how to create and select columns in pandas and have Matplotlib installed. A DataFrame’s index supplies category labels unless you choose columns with x and y.
Bar charts: grouped, stacked, and horizontal
A grouped bar chart places series beside each other. A stacked chart places their values on top of each other. Use a horizontal bar chart when category names are long.
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.plot(x="month", y=["sales", "costs"], kind="bar", rot=0)
plt.show()
df.set_index("month")[["sales", "costs"]].plot.bar(
stacked=True, rot=0
)
plt.show()
df.set_index("month")["sales"].sort_values().plot.barh()
plt.show()The df.plot.bar(...) accessor is equivalent to df.plot(kind="bar", ...). Set an index when its values should become the category axis.
Histograms, box plots, and density plots
These charts describe distributions rather than categories. A histogram counts values in intervals. A box plot shows the median, quartiles, and possible outliers. A density plot estimates a smooth distribution.
| Chart | Best use |
|---|---|
| Histogram | Counts across numeric ranges |
| Box plot | Comparing spread and outliers |
| Density plot | Comparing distribution shapes |
scores = pd.DataFrame({
"math": [60, 65, 70, 70, 75, 80, 95],
"art": [55, 60, 68, 72, 78, 85, 90],
})
scores.plot.hist(bins=5, alpha=0.5)
scores.plot.box()
scores.plot.kde()
plt.show()Scatter plots with size and color
A scatter plot compares two numeric columns. Use s for marker area and c for a numeric color value.
df.plot.scatter(
x="sales",
y="costs",
s=df["sales"] * 2,
c=df["costs"],
colormap="viridis",
colorbar=True,
)
plt.show()Titles, labels, colors, size, and legend
Plot arguments handle common styling. The returned Matplotlib Axes object gives finer control.
ax = df.set_index("month")[["sales", "costs"]].plot(
kind="line",
marker="o",
color=["steelblue", "darkorange"],
figsize=(7, 4),
title="Monthly sales and costs",
)
ax.set_xlabel("Month")
ax.set_ylabel("Units")
ax.legend(title="Measure")
ax.figure.savefig("monthly.png", dpi=150, bbox_inches="tight")
plt.show()Exercise
Which option creates horizontal bars from the sales column?
Show answer
df.set_index("month")["sales"].plot.barh()