A chart has one job: make a pattern in data visible faster than a table would. Most of the skill is choosing the right chart type for the question, and most of the polish is removing things — borders, gridlines, decoration — rather than adding them. This guide covers both, with matplotlib, pandas and seaborn.
Choosing the chart#
| Question | Chart |
|---|---|
| How do categories compare? | bar |
| How has this changed over time? | line |
| How are values distributed? | histogram or box plot |
| Are two variables related? | scatter |
| What are the parts of a whole? | stacked bar (rarely a pie) |
| How do many pairs relate? | heatmap |
Two rules worth following. Bar charts must start at zero — truncating the axis exaggerates differences and is the single most common way charts mislead. And avoid pie charts beyond about three slices; people compare lengths far more accurately than angles, so a bar chart usually communicates the same data better.
The matplotlib model#
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(9, 5))
ax.plot([1, 2, 3, 4], [10, 25, 18, 30], marker="o")
ax.set_title("Monthly total")
ax.set_xlabel("Month")
ax.set_ylabel("Amount")
plt.tight_layout()
plt.savefig("chart.png", dpi=150)
plt.show()
The figure is the canvas; the axes is the plotting area inside it. Almost everything you want to change is a method on the axes. Working with an explicit ax rather than the shorthand plt.plot() is worth the extra line — it makes multi-panel figures straightforward and the code easier to follow.
# Several panels
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
axes[0].bar(names, totals)
axes[0].set_title("Totals")
axes[1].hist(values, bins=20)
axes[1].set_title("Distribution")
plt.tight_layout()
Straight from pandas#
import pandas as pd
df = pd.read_csv("sales.csv", parse_dates=["date"])
# Bar
df.groupby("region")["amount"].sum().plot(kind="barh", figsize=(8, 5))
# Line over time
df.set_index("date")["amount"].resample("M").sum().plot(figsize=(10, 5))
# Distribution
df["amount"].plot(kind="hist", bins=30)
# Two variables
df.plot(kind="scatter", x="visits", y="amount", alpha=0.5)
These call matplotlib underneath, so you can capture the axes and keep customising:
ax = df.groupby("region")["amount"].sum().plot(kind="barh", color="#2563eb")
ax.set_xlabel("Total amount")
ax.set_ylabel("")
ax.set_title("Sales by region")
seaborn#
python -m pip install seaborn
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="whitegrid")
# Distribution by category
sns.boxplot(data=df, x="region", y="amount")
# Relationship, with a fitted line
sns.regplot(data=df, x="visits", y="amount", scatter_kws={"alpha": 0.4})
# Grouped bars with confidence intervals
sns.barplot(data=df, x="region", y="amount", hue="product")
# Correlations
sns.heatmap(df.corr(numeric_only=True), annot=True, fmt=".2f", cmap="coolwarm")
plt.tight_layout()
plt.show()
seaborn understands DataFrames directly, so grouping and colouring by a column is one argument rather than a loop. For statistical charts it removes a great deal of boilerplate.
The five changes that matter#
fig, ax = plt.subplots(figsize=(9, 5))
ax.barh(names, totals, color="#2563eb")
# 1. A title that states the finding, not the variables
ax.set_title("North region accounts for over half of sales", loc="left", fontsize=14)
# 2. Remove chart junk
ax.spines[["top", "right"]].set_visible(False)
# 3. Drop labels the reader can infer
ax.set_ylabel("")
# 4. Format the numbers as people read them
ax.xaxis.set_major_formatter(
plt.FuncFormatter(lambda x, _: f"{x:,.0f}"))
# 5. Label values directly rather than making people read across
for i, value in enumerate(totals):
ax.text(value + 200, i, f"{value:,.0f}", va="center", fontsize=9)
plt.tight_layout()
The title is the biggest single improvement. “Sales by region” tells the reader what the axes already say; “North region accounts for over half of sales” tells them what you want them to notice.
Dates and long labels#
import matplotlib.dates as mdates
fig, ax = plt.subplots(figsize=(10, 5))
ax.plot(df["date"], df["amount"])
ax.xaxis.set_major_locator(mdates.MonthLocator(interval=2))
ax.xaxis.set_major_formatter(mdates.DateFormatter("%b %Y"))
fig.autofmt_xdate() # rotates and aligns the labels
For long category names, a horizontal bar chart avoids rotated labels entirely — rotated text is measurably slower to read.
Colour#
# One highlighted bar, the rest muted
colours = ["#d1d5db"] * len(names)
colours[names.index("North")] = "#2563eb"
ax.barh(names, totals, color=colours)
Three guidelines. Use one colour unless colour encodes something — a rainbow of categories with no meaning adds noise. Do not rely on colour alone, since a meaningful share of readers cannot distinguish red from green; add labels or patterns. And for continuous values use a perceptually uniform map such as viridis rather than jet.
Saving#
plt.savefig("chart.png", dpi=150, bbox_inches="tight")
plt.savefig("chart.svg", bbox_inches="tight") # scalable, for print
plt.savefig("chart.png", dpi=150, transparent=True)
bbox_inches="tight" stops labels being cut off, which is the most common complaint about saved matplotlib figures. Call savefig before show — in some backends, showing the figure clears it.
Interactive charts#
import plotly.express as px
fig = px.scatter(df, x="visits", y="amount", color="region",
hover_data=["customer"], title="Visits against spend")
fig.write_html("chart.html")
fig.show()
Plotly produces charts with hover, zoom and pan, which suit dashboards and anything embedded in a web page. For a static image in a report or a paper, matplotlib gives more control.
A complete example#
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("sales.csv", parse_dates=["date"])
df = df.dropna(subset=["amount", "region"])
totals = (df.groupby("region")["amount"].sum()
.sort_values())
fig, ax = plt.subplots(figsize=(9, 5))
colours = ["#d1d5db"] * len(totals)
colours[-1] = "#2563eb" # highlight the largest
ax.barh(totals.index, totals.values, color=colours)
ax.set_title(f"{totals.index[-1]} leads on total sales",
loc="left", fontsize=14, pad=12)
ax.set_xlabel("Total amount")
ax.set_ylabel("")
ax.spines[["top", "right"]].set_visible(False)
ax.xaxis.set_major_formatter(plt.FuncFormatter(lambda x, _: f"{x:,.0f}"))
for i, value in enumerate(totals.values):
ax.text(value * 1.01, i, f"{value:,.0f}", va="center", fontsize=9)
plt.tight_layout()
plt.savefig("sales_by_region.png", dpi=150, bbox_inches="tight")
Questions people ask#
matplotlib, seaborn or plotly?
matplotlib for full control and static output. seaborn for statistical charts with less code — it is built on matplotlib, so you can mix them. plotly when interactivity is the point.
Why does my chart not appear?
In a script you need plt.show(). In a notebook, charts render automatically. On a headless server there is no display, so save to a file instead.
How do I plot a very large dataset?
Sample it, or aggregate first. A scatter plot of a million points is a solid block that shows nothing; a hexbin or a two-dimensional histogram shows the density.
Should I ever use a pie chart?
Rarely. With two or three slices it is fine. Beyond that, a sorted bar chart communicates the same information more accurately.
Where to go next#
- Python and data science — getting the data into shape first.
- Machine learning with Python — plotting model results.
- The Python standard library — loading CSV and JSON.