Skip to content
Kuza Ndoto Academy

Matplotlib Basics

Beginner → IntermediateChapter 4 · Page 12 of 205 min readUpdated 15 Nov 2026

Matplotlib is Python's original and most widely used plotting library. With a few lines you can draw line, bar, scatter and histogram charts, label them properly and save them as images for a report or presentation.

Two ways to use Matplotlib

Matplotlib offers a quick pyplot style (plt.plot(...), plt.title(...)) and an object-oriented style where you create a figure and axes and call methods on them. The object-oriented style is clearer once a chart has several parts, so this series uses it.

import matplotlib.pyplot as plt

fig, ax = plt.subplots()    # fig = the whole image, ax = one chart area
ax.plot([1, 2, 3], [2, 4, 3])
plt.show()

A Figure is the canvas; an Axes is a single chart on it, with its own x-axis, y-axis, title and data. In a Jupyter notebook the chart appears below the cell; in a script, plt.show() opens a window.

Line charts: change over time

import matplotlib.pyplot as plt

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
revenue = [42000, 38500, 45100, 47800, 51200, 49900]   # KES

fig, ax = plt.subplots(figsize=(8, 4))      # width, height in inches
ax.plot(months, revenue, marker="o", color="tab:green", label="Revenue")
ax.set_title("Monthly revenue, January to June 2026")
ax.set_xlabel("Month")
ax.set_ylabel("Revenue (KES)")
ax.grid(alpha=0.3)
ax.legend()
plt.show()

What the chart shows: a green line with a dot for each month. It dips from KES 42,000 in January to 38,500 in February, climbs steadily to a peak of 51,200 in May, then eases slightly to 49,900 in June. A light grid helps the reader estimate values.

35,000 40,000 45,000 50,000 55,000 Jan Feb Mar Apr May Jun Month Revenue (KES)
Figure 1. A preview of the line chart, drawn from the same six numbers. Like Matplotlib, it zooms the y-axis in on the data range (here 35,000 to 55,000); Matplotlib picks its own tick values, so yours may differ slightly.

Useful plot() options: marker ("o", "s", "^"), linestyle ("-", "--", ":"), linewidth, color and label (used by the legend). Call ax.plot() again on the same axes to add a second line, such as last year's revenue.

Bar charts: comparing categories

counties = ["Nairobi", "Kisumu", "Nakuru"]
county_revenue = [11400, 7420, 3300]

fig, ax = plt.subplots(figsize=(6, 4))
bars = ax.bar(counties, county_revenue, color="tab:blue")
ax.bar_label(bars)                 # write each value on top of its bar
ax.set_title("Revenue by county")
ax.set_ylabel("Revenue (KES)")
plt.show()

What the chart shows: three vertical blue bars. Nairobi's is tallest (11400), Kisumu's is about two-thirds of that (7420) and Nakuru's is shortest (3300), with each number printed above its bar. Use ax.barh() for horizontal bars when category names are long.

0 2,000 4,000 6,000 8,000 10,000 12,000 11400 7420 3300 Nairobi Kisumu Nakuru Revenue (KES)
Figure 2. Preview of the bar chart. Bars start at zero, so their lengths are directly comparable: Nairobi's bar is about 3.5 times Nakuru's.

Scatter plots: relationships

temp_c = [20, 22, 25, 27, 30, 32]
sodas_sold = [110, 125, 120, 150, 160, 175]

fig, ax = plt.subplots()
ax.scatter(temp_c, sodas_sold, color="tab:orange", s=60)   # s = marker size
ax.set_title("Hotter days, more sodas sold")
ax.set_xlabel("Daily high temperature (°C)")
ax.set_ylabel("Sodas sold")
plt.show()

What the chart shows: six orange dots that rise from the bottom-left (20 °C, 110 sodas) to the top-right (32 °C, 175 sodas). The pattern slopes upwards with one small dip at 25 °C, suggesting a strong positive relationship. The Correlation page measures it.

Histograms: distributions

A histogram groups numbers into ranges called bins and shows how many values fall into each.

order_values = [450, 700, 820, 950, 1000, 1100, 1150, 1200, 1250, 1300,
                1400, 1450, 1500, 1600, 1800, 2100, 2400, 3000, 3600, 4500]

fig, ax = plt.subplots()
ax.hist(order_values, bins=[0, 1000, 2000, 3000, 4000, 5000],
        color="tab:purple", edgecolor="white")
ax.set_title("Size of 20 customer orders")
ax.set_xlabel("Order value (KES)")
ax.set_ylabel("Number of orders")
plt.show()

What the chart shows: five touching bars.

Bin (KES)0–9991,000–1,9992,000–2,9993,000–3,9994,000–5,000
Orders411221
0 2 4 6 8 10 12 4 11 2 2 1 0 1,000 2,000 3,000 4,000 5,000 Order value (KES) Number of orders
Figure 3. Preview of the histogram. The tall second bar and the short bars to its right show a right-skewed distribution: most orders are modest, a few are large.

Most orders are between KES 1,000 and 2,000, with a long tail to the right. Each bin includes its left edge, so the KES 1,000 order is counted in the second bar; only the last bin also includes its right edge. You can pass a number instead, such as bins=10, to let Matplotlib choose equal-width bins.

Several charts in one figure

fig, axes = plt.subplots(1, 2, figsize=(10, 4))    # 1 row, 2 columns

axes[0].plot(months, revenue, marker="o")
axes[0].set_title("Monthly revenue")

axes[1].bar(counties, county_revenue)
axes[1].set_title("Revenue by county")

fig.suptitle("Shop performance, 2026")
fig.tight_layout()                       # stop titles and labels overlapping
fig.savefig("shop_report.png", dpi=150, bbox_inches="tight")
plt.show()

What the figure shows: the line chart on the left and the bar chart on the right, side by side under one overall title. The figure is also saved as a sharp PNG image, ready for a report.

Common mistake

Calling plt.show() before savefig(). In a script, closing the window clears the figure, so the saved file is blank. Always save first, then show. Also avoid mixing styles in one chart (plt.title() on one line, ax.set_title() on the next); it can end up labelling the wrong axes when you have subplots.

Plotting straight from pandas

DataFrames and Series have a .plot() method that calls Matplotlib for you, which is quick for exploring:

import pandas as pd

df = pd.DataFrame({"month": months, "revenue": revenue})
ax = df.plot(x="month", y="revenue", kind="bar", legend=False, title="Monthly revenue")
ax.set_ylabel("Revenue (KES)")
plt.show()

What the chart shows: one bar per month with the same values as the line chart above. kind can be "line", "bar", "barh", "hist", "box", "scatter" or "pie", and the method returns an Axes so you can keep customising.

Key points

  • Create charts with fig, ax = plt.subplots(), then call methods on ax.
  • Line for trends, bar for comparisons, scatter for relationships, histogram for distributions.
  • Always add a title, axis labels and units; use bar_label() to show exact values.
  • Save with fig.savefig() before plt.show().
Up next · VisualisationSeabornBeautiful statistical charts.
→

Tip: use the ← and → keys to move between pages.