LearnPy Hub
Data ScienceIntermediateLesson 28 of 32

Matplotlib Charts

Watch the ideaFrom numbers to a chart
x = ["Mon", "Tue", "Wed", "Thu"]
y = [3, 7, 5, 9]

Start with labels for the x-axis and a number for each one.

1Level 1 · BasicsBasics

Numbers in a table are hard to read; a picture makes the pattern jump out. Matplotlib is Python's most widely used plotting library, and every data scientist uses it (pandas and seaborn draw with it behind the scenes). This lesson is a chart guide: for each chart you first see an example picture, then learn what it shows and how to read it, and then the code that draws it. Press Run on the examples below the lesson and the charts appear right under the code.

The first chart downloads Matplotlib into your browser, so give it a few seconds.

Your first plot

303132333435Temperature this weekDay°C12345
This is the picture the code below draws: one line joining five temperatures.

Every chart has the same parts. The x-axis runs along the bottom (here, the day), the y-axis runs up the side (here, the temperature), and the title sits on top. Each point on the line is one (day, temperature) pair. The small marks with numbers on each axis are called ticks.

import matplotlib.pyplot as plt   # plt is the standard nickname

days = [1, 2, 3, 4, 5]
temps = [30, 32, 31, 35, 33]
plt.plot(days, temps)
plt.title("Temperature this week")
plt.xlabel("Day")
plt.ylabel("°C")
plt.show()

Give plot() the x values and the y values (two lists of the same length), add labels, then call plt.show() to display the figure.

Which chart for which question?

Start from the question you want the chart to answer, not from the chart you like. The last column says where in this lesson each chart is taught (the Intermediate and Advanced stages come after this page).

Your questionChartFunctionWhere
How does a value change over time?Lineplt.plot(x, y)Lesson
Which category is biggest?Bar / horizontal barplt.bar(), plt.barh()Lesson
How is one number column spread out?Histogramplt.hist(x, bins=10)Lesson
How do groups compare in centre, spread and outliers?Box plotplt.boxplot([a, b, c])Lesson
Are two numbers related?Scatterplt.scatter(x, y)Lesson
What share of the whole is each part?Pie / donutplt.pie()Lesson
How do two groups compare in each category?Grouped barax.bar(x ± w/2, ...)Intermediate
What is the total, and what is it made of?Stacked bar / areabottom=, ax.stackplot()Intermediate
When did a value jump?Stepax.step()Intermediate
How certain is each average?Error barsax.errorbar()Intermediate
What shape does each group's spread have?Violinax.violinplot()Intermediate
How do 3 or 4 numbers relate at once?Scatter with colour and sizec=, s=, colorbar()Intermediate
Which columns move together?Correlation heatmapax.imshow()Advanced
What do all pairs of columns look like?Scatter matrixpd.plotting.scatter_matrix()Advanced

1. Line chart

120150180210240Monthly salesMonthUnits soldJanFebMarAprMayJun20252026
Example line chart: monthly sales for two years.

What it shows: how a value changes in order, usually over time. Points are joined left to right, so your eye follows the trend: a line going up means the value is growing, a flat line means no change, a dip is a drop.

How to read this one: both years grow, but the orange dashed 2026 line sits above the blue 2025 line every month, so 2026 sold more. Several lines on one chart make comparisons easy; the legend box says which line is which.

plt.plot(months, sales_2025, marker="o", label="2025")
plt.plot(months, sales_2026, marker="s", linestyle="--", label="2026")
plt.legend()                 # shows the key using each label
plt.grid(True, alpha=0.3)    # light grid lines

marker draws a dot or square on each point, linestyle="--" makes the line dashed, and label is the name the legend shows.

2. Bar chart

020406080100Class average by subjectAverage markMathPhysicsChemistryEnglishICT7871668288
Example bar chart: the class average in each subject.

What it shows: a comparison between separate categories. Each category gets one bar, and the bar's height is its value. The order of the bars doesn't mean time; you simply compare heights.

How to read this one: ICT has the tallest bar (88) and Chemistry the shortest (66). Bars should start at zero, otherwise small differences look huge.

bars = plt.bar(subjects, averages, color="steelblue")
plt.ylim(0, 100)             # y-axis from 0 to 100
for bar, value in zip(bars, averages):
    plt.text(bar.get_x() + bar.get_width() / 2, value + 1, str(value), ha="center")

plt.bar() takes the category names and their values. The loop writes each number just above its bar with plt.text(x, y, text); ha="center" centres the text horizontally.

3. Horizontal bar chart

Total sales by region05001000150020002500KhulnaSylhetDhakaSales (Tk)
Example: a horizontal bar chart of total sales per region.

What it shows: the same thing as a bar chart, turned sideways. Use it when the category names are long (they fit on the left instead of being squashed under the bars) or when there are many categories. Sort the values first so the longest bar is on top; then the ranking can be read at a glance.

regions = ["Khulna", "Sylhet", "Dhaka"]     # smallest first, so the biggest ends up on top
totals = [750, 1100, 2350]
plt.barh(regions, totals, color="slateblue")
plt.xlabel("Sales (Tk)")

plt.barh(names, values) puts the names on the y-axis and the values on the x-axis, so the label you need is xlabel. In ML you'll draw exactly this chart for feature importance (which input columns matter most to a model).

4. Histogram

0481216How marks are spreadMarksNumber of students30405060708090100
Example histogram: how the 60 students' marks are spread.

What it shows: how one list of numbers is spread out (its distribution). Matplotlib cuts the range into equal slices called bins (here 30–40, 40–50, …) and the height of each bar is how many values fall in that bin. The bars touch because the bins follow straight on from each other.

How to read this one: most students scored between 40 and 70, and only a few scored very low or very high. A histogram shows the centre, the spread and any odd values at a glance. It looks like a bar chart, but a bar chart compares categories while a histogram counts numbers.

plt.hist(marks, bins=7, color="seagreen", edgecolor="white")
plt.xlabel("Marks")
plt.ylabel("Number of students")

You give plt.hist() just the raw values; it does the counting. edgecolor="white" draws a thin gap between bars.

Choosing the number of bins

07142128406080bins=402468406080bins=20same 60 marks: too few bins hide detail, too many make noise
Example: the same data drawn with 4 bins and with 20 bins.

The bins setting changes the picture a lot. With too few bins everything is lumped together and the shape disappears; with too many each bin holds only one or two values and the chart turns into noise. Between 10 and 30 bins is a good start for a few hundred values; try several. You can also pass the bin edges yourself, for example bins=[0, 40, 60, 80, 100]. Shapes to look for: one hump in the middle (symmetric), a long tail to one side (skewed, common for prices and incomes), or two humps (bimodal: two different groups are mixed together).

5. Box plot

30405060708090100Section ASection BSection CMarksMarks in three sectionsmax (top whisker)Q3: 75% belowmedian: middleQ1: 25% belowmin (low whisker)outlierbox = IQR (Q3 − Q1)whiskers: ≤ 1.5 × IQR
Example box plot: each box summarises one section's 30 marks.

What it shows: a five-number summary of a list of numbers, drawn as a box with "whiskers" (that's why it's also called a box-and-whisker plot). Put several boxes side by side and you can compare whole groups in one look, which is why box plots are used everywhere in data science.

To read a box, imagine the values sorted from smallest to largest:

PartMeaning
Median (orange line)The middle value: half the values are below it, half above. Unlike the mean, one extreme value hardly moves it.
Q1 (bottom of the box)The first quartile: 25% of values are below it.
Q3 (top of the box)The third quartile: 75% of values are below it.
IQR (height of the box)The interquartile range, Q3 − Q1. The middle 50% of values sit inside the box. A tall box means a big spread.
WhiskersLines from the box out to the smallest and largest values that are not outliers. They reach at most 1.5 × IQR beyond the box.
Outliers (circles)Values below Q1 − 1.5 × IQR or above Q3 + 1.5 × IQR, drawn one by one. They may be mistakes or genuinely unusual cases; look at them before deleting anything.

How to read this one: Section C has the highest median and a short box, so most of its students scored similarly well, except one outlier near 38. Section B's median is lowest and its box is tallest: its marks are the most spread out. Section A sits in between, with two low outliers. Comparing medians and box heights is usually more honest than comparing averages alone.

import numpy as np
q1, median, q3 = np.percentile(marks, [25, 50, 75])
iqr = q3 - q1
outliers = marks[(marks < q1 - 1.5 * iqr) | (marks > q3 + 1.5 * iqr)]

fig, ax = plt.subplots()
ax.boxplot([section_a, section_b, section_c])   # one box per list
ax.set_xticks([1, 2, 3])                        # boxes sit at x = 1, 2, 3
ax.set_xticklabels(["Section A", "Section B", "Section C"])

boxplot() takes a list of lists (or arrays), one per group, and works out every number itself. The boxes are placed at x = 1, 2, 3, …, so you name them with set_xticks and set_xticklabels. (Newer Matplotlib versions also accept tick_labels=, but this way works in every version.) Add vert=False for horizontal boxes, and patch_artist=True if you want to fill the boxes with colour.

6. Scatter plot

30507090Study hours vs marksHours studiedMarks0246810
Example scatter plot: each dot is one student.

What it shows: whether two numbers are related. Each dot is one item (here, one student): its x position is one measurement (hours studied) and its y position is another (marks). Dots are not joined, because the items are separate.

How to read this one: the cloud of dots rises from bottom left to top right, so students who studied more usually scored more. That's a positive relationship (or positive correlation). A cloud going down would be a negative one, and a shapeless cloud means no clear link. Dots far away from the cloud are outliers worth checking.

plt.scatter(hours, marks, color="darkorange", alpha=0.7)
plt.xlabel("Hours studied")
plt.ylabel("Marks")

plt.scatter(x, y) needs two lists of the same length: the first item of each list makes the first dot, and so on. alpha (0 to 1) makes dots see-through so overlapping dots show up darker. In the Intermediate stage you'll colour and size the dots by a third and fourth number.

7. Pie and donut charts

Where my monthly allowance goes52%Food17%Transport14%Books7%Mobile10%Other
Example pie chart: how a monthly allowance is spent.

What it shows: how a whole is split into parts. The full circle is 100%, and each slice's size is its share of the total.

How to read this one: Food takes about half of the money (52%), and Mobile the smallest part (7%). Pie charts work for a few parts only; with many slices, or slices of similar size, a bar chart is easier to compare.

plt.pie(spending.values(), labels=spending.keys(),
        autopct="%1.0f%%", startangle=90)

plt.pie() takes the amounts and works out the percentages itself. autopct prints the percentage on each slice, and startangle=90 starts the first slice at the top.

Monthly allowance (donut)Food52%Transport17%Books14%Mobile7%Other10%TotalTk 8700
Example donut chart: a pie with the centre cut out, so the total can sit in the middle.

A donut chart is a pie with the centre cut out. It reads the same way, and the hole is a handy place for the total. You make it with the same function by giving each wedge a width smaller than the radius (the radius is 1):

plt.pie(amounts, labels=names, autopct="%1.0f%%", startangle=90,
        pctdistance=0.8, wedgeprops={"width": 0.4})
plt.text(0, 0, "Tk 8700", ha="center", va="center")

wedgeprops={"width": 0.4} keeps only the outer 40% of each slice, and pctdistance=0.8 moves the percentages onto the ring.

8. Styling: colours, markers, lines, legend, grid, size

05101520123456Same data, three stylesxysolid, circlesdashed, squaresdotted, triangles
Example: colours, markers and line styles, drawn with the ggplot style sheet.

Almost every plotting function accepts the same style options:

OptionExamplesWhat it changes
color"red", "tab:blue", "#3b6fd8"colour by name, from the default palette, or as a hex code
marker"o", "s", "^", "x", "."circle, square, triangle, cross or small dot on each point
linestyle"-", "--", ":", "-."solid, dashed, dotted, dash-dot
linewidth, markersize2.5, 8thickness of the line, size of the markers
alpha0.5transparency (0 = invisible, 1 = solid)
label + plt.legend()plt.legend(loc="upper left")the key; loc picks its corner
plt.grid()plt.grid(True, alpha=0.3)light guide lines behind the data
figsizeplt.figure(figsize=(8, 4))width and height of the figure in inches
xlim, ylimplt.ylim(0, 100)the range each axis shows

There is also a short format string: plt.plot(x, y, "o--") means circle markers with a dashed line, and "r^:" means red triangles with a dotted line.

A style sheet changes the look of the whole figure at once (background, grid, colours, fonts). plt.style.available lists them; "ggplot", "bmh", "fivethirtyeight" and "grayscale" exist in every version. Use one for a single figure with a with block, so your other charts keep the default look:

with plt.style.context("ggplot"):
    fig, ax = plt.subplots(figsize=(7, 4))
    ax.plot(x, y1, color="tab:red", marker="o", label="solid, circles")
    ax.legend()
    plt.show()

plt.style.use("ggplot") switches the style for everything that follows instead.

9. Figures and axes: the object-oriented way

050100MarksAnaBenCy02040SalesJanFebMarAprone figure (fig), two axes: ax1 on the left, ax2 on the right
Example figure with two axes side by side.

The whole picture is the figure; each chart inside it is an axes. For more control, and for several charts side by side, use plt.subplots() and call methods on each axes:

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 3.5))
ax1.bar(names, marks)
ax1.set_title("Marks")
ax2.plot(months, sales)
ax2.set_title("Sales")
plt.tight_layout()
plt.show()

subplots(1, 2) means 1 row and 2 columns. Note the names change slightly: plt.title() becomes ax.set_title(), plt.xlabel() becomes ax.set_xlabel() and plt.ylim() becomes ax.set_ylim(). tight_layout() stops titles and labels from overlapping. Most data science code uses this style, and the stages build bigger grids with it.

10. Plotting straight from pandas

5060708090100mathphysicsenglishkind="box"5070905060708090100mathphysicskind="scatter"
Example: df.plot(kind="box") and df.plot(kind="scatter", x="math", y="physics").

DataFrames and Series have a .plot() method that uses Matplotlib behind the scenes, so one line often replaces five. Choose the chart with kind=:

CodeDraws
df.plot() or kind="line"one line per numeric column, with the index on the x-axis
s.plot(kind="bar") / "barh"one bar per row (great after groupby or value_counts())
df["math"].plot(kind="hist", bins=5)a histogram of one column
df.plot(kind="box")one box per numeric column, side by side
df.plot(kind="scatter", x="math", y="physics")a scatter of two columns
s.plot(kind="pie"), kind="area"a pie, or a stacked area chart

.plot() returns the axes it drew on, so you can keep styling it with ax.set_title() and friends. To place a pandas chart inside your own grid, pass ax=: df.plot(kind="box", ax=axes[0]). For a box plot per group, use df.boxplot(column="marks", by="section").

11. Saving a chart to a file

For reports, slides and project write-ups you need an image file. Call savefig before plt.show() (showing can clear the figure):

fig.savefig("marks.png", dpi=150, bbox_inches="tight")

The file type comes from the name: .png for slides and web pages, .svg or .pdf for sharp printing. dpi (dots per inch) sets the sharpness, and bbox_inches="tight" trims empty margins so labels aren't cut off. Here in the browser the file is saved in a temporary folder; on your own computer it appears next to your script.

Key points: import matplotlib.pyplot as plt; start from the question and pick the chart that answers it (line for trends, bar for comparing categories, histogram for one column's spread, box plot for comparing groups' median, spread and outliers, scatter for relationships, pie or donut for a few parts of a whole); choose bins with care; always add a title and axis labels with units; use fig, ax = plt.subplots() and ax.set_... methods for real work; df.plot(kind=...) charts a DataFrame in one line; save with fig.savefig() before plt.show().

See it in actionWhat a bar chart does

A bar chart turns each number into a bar of matching length. Here the bars are drawn with # in the output; Matplotlib draws real ones in the examples below.

Step-by-step

Try it yourselfExample 1: A line chart

Two lines with labels, markers and a legend. Change the numbers and run again.

example_1.py
Output appears here
Fill in the blanks

Draw a line

Fill the blanks so the program draws a line chart of the data and labels the x-axis. It prints ready when done.

blanks.py
import matplotlib.pyplot as plt
plt.([1, 2, 3], [2, 4, 9])
plt.("Day")
print("ready")
Fix the bug

Mismatched data

This should plot 4 days of temperatures and print plotted 4 points, but it crashes. The x and y lists must be the same length. Fix the days list.

buggy.py

Example 2: A bar chart

Bars compare categories. The loop writes each value above its bar.

example_2.py
Output appears here
Fill in the blanks

A bar chart

Fill the blank to draw a bar chart, and the blank to give it a title. It prints the number of bars: 3.

blanks.py
import matplotlib.pyplot as plt
bars = plt.(["Mon", "Tue", "Wed"], [5, 3, 7])
plt.("Steps")
print(len(bars))

Example 3: A horizontal bar chart

Sorting first puts the biggest bar on top. Try adding a region with a long name.

example_3.py
Output appears here
Your turn

Scatter the points

Make a scatter plot of hours studied [1, 2, 3, 4, 5] against marks [40, 50, 65, 70, 85], then print the highest mark plotted: 85.

my_code.py

Example 4: A histogram and the effect of bins

The same 60 marks drawn with 4, 10 and 20 bins. np.histogram prints the counts that the bars show.

example_4.py
Output appears here
Your turn

Pie chart slices

Draw a pie chart of [40, 35, 25] with labels Rice, Fish, Veg, then print how many slices it has: 3.

my_code.py

Example 5: A box plot of three sections

The loop prints each box's numbers, so you can match them to the picture. Section C has one student who had a bad day.

example_5.py
Output appears here

Example 6: A scatter plot

Each dot is one student. np.corrcoef measures how closely the dots follow a straight line (1 = perfectly, 0 = not at all).

example_6.py
Output appears here

Example 7: A pie chart and a donut chart

Same data twice. The donut uses wedgeprops to cut out the centre and writes the total in the hole.

example_7.py
Output appears here

Example 8: Styling and a style sheet

Colours, markers, line styles, a legend and a grid, all inside the ggplot style sheet. Change "ggplot" to "bmh" or "grayscale".

example_8.py
Output appears here

Example 9: Two charts in one figure

plt.subplots(1, 2) gives one figure with two axes. Each axes gets its own title.

example_9.py
Output appears here

Example 10: Plotting a pandas DataFrame

Four pandas chart kinds placed in one 2×2 grid with ax=. describe() prints the numbers behind the box plot.

example_10.py
Output appears here

Example 11: Saving a chart with savefig

savefig writes the image before plt.show(). The program then checks that the file exists.

example_11.py
Output appears here

2Level 2 · IntermediateMore chart types: groups, totals, uncertainty and shape

The main lesson covered the everyday charts. This stage adds the charts you need once you compare groups, show what a total is made of, or report results from experiments and models.

Grouped bar chart

02040603050354545405042JanFebMarAprOrders: online vs shopOrdersonlineshop
Example grouped bar chart: two bars per month, side by side.

What it shows: two (or more) values for every category, standing side by side. Use it when the question is "within each month, which channel won?". Here online overtakes the shop in March.

x = np.arange(len(months))          # 0, 1, 2, 3: one slot per month
w = 0.38                            # width of one bar
ax.bar(x - w / 2, online, width=w, label="online")
ax.bar(x + w / 2, shop, width=w, label="shop")
ax.set_xticks(x)
ax.set_xticklabels(months)

Each group is shifted half a bar to the left or right of its slot, then the tick labels are put back in the middle.

Stacked bar chart

02040608010012080808592JanFebMarAprOrders: total split by channelOrdersshoponline
Example stacked bar chart: the parts are piled up, so the top of each bar is the total.

What it shows: the same data piled up: the full height is the total and the coloured pieces are its parts. Use it when the total matters most. Only the bottom piece is easy to compare between bars, because the others don't start from the same line.

ax.bar(months, online, label="online")
ax.bar(months, shop, bottom=online, label="shop")   # start where online ends

Area chart (stackplot)

0501001502020202220242026Visits by device (thousands)Visitstabletdesktopmobile
Example area chart (stackplot): bands piled on top of each other over time.

What it shows: a stacked chart over time. Each band is one part, and the top edge is the total. Here total visits grow, and the blue mobile band takes a bigger and bigger share while desktop shrinks.

ax.stackplot(years, mobile, desktop, tablet,
             labels=["mobile", "desktop", "tablet"], alpha=0.85)
ax.legend(loc="upper left")

For a single shaded area use ax.fill_between(x, y): it fills the space between the line and zero (or between two lines, ax.fill_between(x, low, high, alpha=0.2), which is how a range or a confidence band is drawn around a line).

Step chart

1520253012345678Students enrolledWeekStudents
Example step chart: the value holds steady, then jumps.

What it shows: a value that stays the same and then jumps, such as enrolments, prices, stock levels or a model's learning rate. A normal line would draw a slope between points, suggesting a smooth change that never happened.

ax.step(weeks, enrolled, where="post", marker="o")

where="post" keeps each value until the next point, which is what "it stayed 20 until week 3" means.

Error bars

0.700.750.800.850.900.950.8700.7980.9000.828LogRegTreeForestKNN5-fold accuracy (mean ± 1 std)Accuracy
Example error bars: the dot is the mean, the bar shows how much the 5 scores vary.

What it shows: an average plus how much it varies. In ML you test a model several times (for example with 5-fold cross-validation, which trains and tests it on 5 different splits of the data) and report the mean ± standard deviation. The standard deviation measures how far the scores usually are from their mean. Long bars mean the result is unreliable.

How to read this one: Forest has the best mean and a short bar, so it is both good and steady. Tree's bar is long: its score depends a lot on the split. When two bars overlap a lot, don't claim one model is clearly better.

ax.errorbar(x, means, yerr=stds, fmt="o", capsize=6)

yerr is the length of the bar above and below each point, fmt="o" draws dots without a joining line, and capsize adds the little caps.

Violin plot

30507090median 64median 64Group AGroup BSame median, different shapesMarks
Example violin plot: the width shows where values are common.

What it shows: the full shape of each group's distribution. It's like a box plot mixed with a smooth histogram turned on its side: the violin is wide where values are common and thin where they're rare.

How to read this one: both groups have a median of about 64, and their box plots would look similar. But group B's violin has two bulges: its students are either weak (around 50) or strong (around 80), with hardly anyone in the middle. A box plot hides that; a violin shows it.

ax.violinplot([group_a, group_b], showmedians=True)
ax.set_xticks([1, 2])
ax.set_xticklabels(["Group A", "Group B"])

Scatter with colour, size and a colour bar

03060901205001000150020002500Flats: size, price and ageArea (sq ft)Price (lakh Tk)010203040age (years)
Example: x and y are numbers, colour is a third number (age) and dot size a fourth (rooms).

A scatter plot can show four numbers at once: x, y, colour and size. Here bigger flats cost more (x and y), dark purple dots are new and yellow dots are old (colour = age), and big dots have more rooms (size).

sc = ax.scatter(area, price, c=age, s=rooms * 25, cmap="viridis", alpha=0.8)
fig.colorbar(sc, ax=ax, label="age (years)")

c= gives one number per dot, and the colormap (cmap) turns numbers into colours. "viridis" is a good default: it goes from dark to light, so it even works in black and white and for colour-blind readers. The colour bar is the key that says which colour means which number; without it, the colours mean nothing. s= is the dot area in points². In classification you'll often pass the class labels as c=y to see whether the classes form separate clouds.

Example 12: Grouped and stacked bars

The same data drawn both ways. Grouped bars compare the channels; stacked bars show the total.

example_12.py
Output appears here

Example 13: An area chart and a step chart

stackplot piles the bands up over time; step draws flat stretches and sudden jumps, and fill_between shades the area under it.

example_13.py
Output appears here

Example 14: Error bars for model scores

Each model was tested 5 times. The dot is the mean and the bar is one standard deviation each way.

example_14.py
Output appears here

Example 15: Box plot vs violin plot

Group B is really two groups mixed together. The box plot hides it; the violin shows two bulges.

example_15.py
Output appears here

Example 16: Scatter with colour, size and a colour bar

Four numbers per flat: area (x), price (y), age (colour) and rooms (dot size). Try cmap="plasma".

example_16.py
Output appears here

3Level 3 · AdvancedMulti-panel figures, heatmaps and pairwise views

Real projects need figures that tell a whole story: several aligned panels, two units on one chart, notes that point at what matters, and overviews of a whole dataset. These are the tools for that.

Subplot grids and shared axes

00.51.0Losstrainval0.40.71.0Accuracy0.0010.010.105101520epochLearning rate (log)00.20.405101520epochVal − train loss
Example 2×2 grid with sharex=True: only the bottom row needs epoch numbers.

plt.subplots(2, 2) returns the figure and a 2×2 array of axes, so you pick a panel with axes[row, col]. With sharex=True all panels use the same x range, zooming one zooms all, and only the bottom row prints the tick numbers. (sharey=True does the same for y; use it when panels must be compared by height.)

fig, axes = plt.subplots(2, 2, figsize=(10, 6), sharex=True)
axes[0, 0].plot(epochs, train_loss, label="train")
axes[1, 0].step(epochs, lr, where="post")
axes[1, 0].set_yscale("log")
for ax in axes[1]:              # bottom row
    ax.set_xlabel("epoch")
fig.suptitle("Training a model: 20 epochs")
fig.tight_layout()

This is a typical ML training dashboard. Training loss keeps falling, but validation loss (on data the model hasn't seen) reaches its lowest point at epoch 12 and then rises, while the gap between the two keeps growing: the model is starting to overfit, which means it memorises the training data instead of learning patterns that carry over to new data. Use axes.flat to loop over every panel, and fig.suptitle() for one title over the whole figure.

Two y-axes

0100200300400313233MayJunJulAugSepDhaka monsoonrain (mm)temperature (°C)
Example: ax.twinx() gives the line its own y-axis on the right.

ax2 = ax.twinx() creates a second axes that shares the x-axis but has its own y-axis on the right. Use it when two measures have different units (rain in mm, temperature in °C). Colour each axis label like its data so readers know which scale to use, and don't overuse it: two scales make it easy to suggest links that aren't real.

ax.bar(months, rain, color="#7fb3ff")
ax.set_ylabel("rain (mm)")
ax2 = ax.twinx()
ax2.plot(months, temp, color="#d9534f", marker="o")
ax2.set_ylabel("temperature (°C)", color="#d9534f")

Annotations, text and arrows

304050607080target 50best day!38: lowestSunMonTueWedThuTea cups soldCups
Example: ax.axhline() draws the target, ax.annotate() adds the arrow and text.

A good chart points at its main message. ax.annotate(text, xy=point, xytext=where_the_text_goes, arrowprops={...}) writes a note with an arrow to a data point. ax.text(x, y, text) writes text without an arrow, and ax.axhline(y) / ax.axvline(x) draw a full-width reference line such as a target or a threshold.

ax.axhline(50, color="gray", linestyle="--", label="target")
best = cups.index(max(cups))
ax.annotate("best day!", xy=(best, cups[best]), xytext=(best - 1.5, cups[best] + 5),
            arrowprops={"arrowstyle": "->"}, fontweight="bold")
ax.text(2.1, 36, "38: lowest", color="gray")

With text labels on the x-axis, the categories sit at x = 0, 1, 2, …, so the point for the 4th day is at x = 3.

Heatmap of a correlation matrix

1.00-0.04-0.760.740.90hours-0.041.000.04-0.110.09sleep-0.760.041.00-0.55-0.76phone0.74-0.11-0.551.000.61attendance0.900.09-0.760.611.00markshourssleepphoneattendancemarksCorrelation matrix-1-0.500.51
Example: imshow colours each cell, ax.text writes the value and the colour bar is the key.

A heatmap colours each cell of a table. Its most common use in data science is the correlation matrix: df.corr() gives a number from −1 to 1 for every pair of columns. Near 1 means they rise together, near −1 means one rises as the other falls, and near 0 means no straight-line link. The diagonal is always 1 (each column with itself).

How to read this one: marks are strongly linked to study hours (0.90) and attendance (0.61), and negatively to phone time (−0.76); sleep shows almost no straight-line link. Hours and phone are also linked to each other (−0.76), so a model that uses both is partly counting the same thing twice. Remember that correlation is not causation.

corr = df.corr(numeric_only=True)
im = ax.imshow(corr.values, cmap="coolwarm", vmin=-1, vmax=1)
ax.set_xticks(range(len(corr)))
ax.set_xticklabels(corr.columns, rotation=35, ha="right")
ax.set_yticks(range(len(corr)))
ax.set_yticklabels(corr.columns)
for i in range(len(corr)):
    for j in range(len(corr)):
        ax.text(j, i, f"{corr.iloc[i, j]:.2f}", ha="center", va="center")
fig.colorbar(im, ax=ax, label="correlation")

imshow draws row i, column j of the array at x = j, y = i. vmin=-1, vmax=1 fixes the colour range so 0 is the neutral middle colour; "coolwarm" is a diverging colormap (two colours meeting at a neutral middle), right for data with a meaningful zero. The same code draws a confusion matrix or marks by student and subject.

Scatter matrix: every pair at once

sepal lenpetal lensepal lenpetal widpetal lenpetal widsetosaversicolorvirginica
Example scatter matrix: every pair of columns in one picture (a few flowers shown per species).

pd.plotting.scatter_matrix(df) draws a grid with a scatter plot for every pair of numeric columns and a histogram of each column on the diagonal. It's the fastest way to explore a new dataset before modelling. Colour the dots by class and you can see which features separate the classes: in the iris flowers above, petal length and petal width split the three species almost perfectly, while sepal length overlaps more.

colours = df["target"].map({0: "tab:blue", 1: "tab:orange", 2: "tab:green"})
pd.plotting.scatter_matrix(df[cols], c=colours.tolist(), figsize=(8, 8), diagonal="hist")

With many columns the grid gets crowded; pick the 3 to 6 most interesting ones first. (The seaborn library's pairplot draws the same idea with less code.)

Log scales, clean style and saving for reports

ax.set_yscale("log") shows values that grow by multiplying (users, populations, file sizes, learning rates) as straight lines and keeps small values visible next to huge ones. For finished figures: label every axis with units, remove clutter with ax.spines[["top", "right"]].set_visible(False), use colour only when it means something, and keep the same colour for the same thing across charts. Then save with fig.savefig("name.png", dpi=200, bbox_inches="tight"), or .svg / .pdf for sharp printing.

Example 17: A 2×2 training dashboard with sharex

Four panels share one epoch axis. The dotted line marks the epoch with the lowest validation loss, where overfitting starts.

example_17.py
Output appears here

Example 18: Annotations, text and a target line

Change the numbers in cups; the arrow always finds the best day.

example_18.py
Output appears here

Example 19: Two y-axes and saving to a file

Rain uses the left axis (bars), temperature the right axis (line). savefig writes the image before it is shown.

example_19.py
Output appears here

Example 20: A correlation heatmap

Red cells are strong positive links, blue cells negative. White text is used on dark cells so it stays readable.

example_20.py
Output appears here

Example 21: A scatter matrix of the iris flowers

load_iris is a small dataset bundled with scikit-learn (you'll use it again in the scikit-learn lesson). Dots are coloured by species.

example_21.py
Output appears here

Example 22: Log scale, clean style and saving

The same growth on a linear and a log scale, with the top and right borders removed, saved as PNG and SVG.

example_22.py
Output appears here
Good practiceA chart without labels is a puzzle. Always add a title and axis labels (with units), start bar charts at zero, and prefer bar charts to pie charts when there are more than a few categories, because people compare lengths far more accurately than angles. When you compare groups, show the spread (a box plot or histogram), not just the averages.
Exercise · predict the output

What does this program print? (It finds the median and the outliers, exactly as a box plot does.)

import numpy as np
data = np.array([2, 4, 4, 5, 7, 9, 30])
q1, med, q3 = np.percentile(data, [25, 50, 75])
iqr = q3 - q1
print(med, data[data > q3 + 1.5 * iqr])
Quick quiz · 10 questions
1. Which chart is best for showing change over time?
2. Which function draws a bar chart?
3. In a box plot, what does the line inside the box show?
4. In a box plot, the height of the box (Q3 − Q1) is called what?
5. What happens if a histogram has far too many bins?
6. You want to see whether house size and price are related. Which chart fits?
7. How do you turn plt.pie into a donut chart?
8. What does plt.subplots(1, 2) create?
9. With fig, ax = plt.subplots(), how do you set the title?
10. Which line draws one box per numeric column of a DataFrame df?
Ready to practice matplotlib charts?

50 graded problems are waiting in Topic Practice.

Practice this topic →
Python Matplotlib Charts · LearnPy Hub