Visualizing Data with Matplotlib and seaborn
Choose the right chart for each question, build line, bar, histogram and scatter plots with Matplotlib and seaborn, and avoid charts that mislead.
Welcome back!
Step 1 of 12Learn
Why you plot before you trust a number
In 1973, statistician Francis Anscombe published four small datasets, now called Anscombe's quartet. All four have nearly identical means, variances, correlation (about 0.82) and best-fit line. Plotted, they look nothing alike: one is a tidy linear cloud, one is a smooth curve, one is a perfect line spoiled by a single outlier, and one is a vertical stack of points with one far-off value creating the whole "correlation".
The lesson has held for fifty years: summary statistics can hide the shape of the data, and charts reveal it. Plotting is part of exploration, not just decoration for the final report.
Python's core plotting library is Matplotlib:
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(daily["date"], daily["rentals"])
ax.set_title("Daily rentals, 2026")
ax.set_xlabel("Date")
ax.set_ylabel("Rentals")
plt.show()The fig, ax = plt.subplots() pattern creates a figure and an axes object to draw on, which scales cleanly to several charts side by side: fig, axes = plt.subplots(1, 3).
pandas has plotting shortcuts built on Matplotlib, such as df.plot(x="date", y="rentals") and df["age"].plot.hist(bins=20). seaborn adds statistical charts with good defaults and works directly with long-format DataFrames: sns.scatterplot(data=df, x="temp", y="rentals", hue="weekday").
Step 2 of 12Practice · True or false
Four datasets with the same mean, variance and correlation must look essentially the same when plotted.
Step 3 of 12Learn
Matching the chart to the question
Most analytical charts answer one of a few questions. Pick the chart by the question, not by what looks impressive.
| Question | Chart | Matplotlib / seaborn |
|---|---|---|
| How does it change over time? | Line chart | ax.plot, sns.lineplot |
| How do categories compare? | Bar chart | ax.bar, sns.barplot, sns.countplot |
| How are values distributed? | Histogram or box plot | ax.hist, sns.histplot, sns.boxplot |
| How do two numeric variables relate? | Scatter plot | ax.scatter, sns.scatterplot |
| How do two categories combine? | Heatmap | sns.heatmap on a pivot table |
Some practical rules:
- Bar charts start at zero. Bar length encodes the value, so a truncated axis exaggerates differences.
- Sort bars by value unless the categories have a natural order, such as months.
- Avoid pie charts with more than a few slices; people compare lengths far more accurately than angles.
- Label everything: title, axis labels with units, and a legend only when there are several series.
- Use color with purpose: highlight the one series that matters and gray out the rest, and choose colorblind-friendly palettes.
A chart should make one point clearly. If you need a paragraph to explain how to read it, try a simpler chart.
Step 4 of 12Practice · Match the pairs
Match each question to the chart type that answers it best.
Tap an answer, then tap the place where it belongs (or drag it there).
- How did weekly website visits change over the past year?
- Which of eight product categories had the most returns?
- What does the distribution of customer ages look like?
- Do houses with more square feet sell for more?
- Which hour-and-weekday combinations are busiest?
Step 5 of 12Learn
Histograms and the bins question
A histogram splits a numeric range into bins and draws a bar for how many values fall into each. It's the first chart to make for any numeric column, because it shows the shape: symmetric or skewed, one peak or two, gaps, and suspicious spikes such as a pile of values at exactly 0 or 999.
The number of bins changes what you see:
- Too few bins smooth away real structure; two peaks can merge into one.
- Too many bins turn the chart into noise, with lots of tiny bars of 0 or 1.
With equal-width bins, each bin's width is (max − min) ÷ number of bins. For ages from 18 to 78 with 12 bins, each bin covers 5 years.
ax.hist(df["age"], bins=12, edgecolor="white")
sns.histplot(df["age"], bins=12, kde=True) # kde adds a smooth density curveTry a few bin counts; there's no single right one. Box plots (sns.boxplot(data=df, x="station", y="bikes_out")) summarize a distribution as median, quartiles and IQR-rule whiskers, and they shine when comparing many groups side by side. Histograms show more detail for one group at a time.
Step 6 of 12Practice · Work it out
Delivery times range from 0 to 90 minutes. A histogram uses 18 equal-width bins. How many minutes wide is each bin?
Step 7 of 12Learn
Charts that mislead
Charts can deceive, usually by accident. Watch for these patterns, both in your own work and in charts you're shown:
- Truncated bar axes. Two bars at 50.1 and 50.6 look wildly different if the y-axis starts at 50. For bars, start at zero. (Line charts may zoom in, as long as the axis is clearly labeled.)
- Inconsistent scales. Two side-by-side charts with different y-axis ranges invite wrong comparisons. Use
sharey=Trueinplt.subplots. - Cherry-picked time windows. Showing only the three months after a low point makes any trend look like a boom.
- Totals instead of rates. A map of total crimes mostly shows where people live. Per-capita rates answer the real question.
- Dual y-axes. Two unrelated series on two scales can be made to appear correlated just by adjusting the scales.
- 3D effects. Perspective distorts the size of bars and slices.
A good habit before publishing: ask what a busy reader would conclude in five seconds, and whether that conclusion is true.
Step 8 of 12Practice · What would you do?
What would you do?
A slide shows two bars: "Our product: 96% satisfaction" and "Competitor: 92% satisfaction". The y-axis runs from 90% to 97%, so the competitor's bar looks about half as tall. What's the problem?
Step 9 of 12Note
Step 10 of 12Learn
Charts for an audience
Exploratory charts are for you: quick, rough and numerous. Explanatory charts are for other people, and they deserve more care, because a reader gives a chart a few seconds before moving on.
Turn an exploratory chart into an explanatory one:
- Lead with the message. Use the title to state the finding, such as "Downtown stations run out of bikes by 8:30 a.m. on weekdays", rather than a label like "Bikes available by hour".
- Remove clutter. Drop heavy gridlines, borders, unnecessary legends and decimals nobody needs.
- Highlight what matters. Draw the key series in a strong color and everything else in gray; add a short annotation at the important point.
- Use readable sizes. Fonts that look fine on your laptop are often unreadable on a projector.
- Show uncertainty when it matters, for example a shaded band around a forecast.
Accessibility counts too. About 1 in 12 men and 1 in 200 women have some form of color vision deficiency, so don't rely on red versus green alone; seaborn's "colorblind" palette helps, and direct labels on lines beat a separate legend.
A useful test: show the chart to someone for five seconds, take it away, and ask what it said. If their answer matches your message, the chart works.
Step 11 of 12Practice · Choose one
Which title best suits an explanatory chart for a management meeting?
Step 12 of 12Practice · Choose one
You want to compare the distribution of delivery times across six warehouses in one chart. Which is the best choice?
Lesson complete!