Matplotlib Basics: Charts That Actually Communicate

Matplotlib Basics: Charts That Actually Communicate – DataScienceWay tutorial

A good chart makes a point in seconds; a poor one confuses or, worse, misleads. Matplotlib is the foundation of plotting in Python – pandas, seaborn and many other libraries build on it – so learning its core ideas pays off whatever tools you end up using.

This tutorial focuses on charts that communicate. You will learn the figure-and-axes model, the four chart types that cover most business needs (line, bar, histogram, scatter), how to label and annotate properly, how to put several charts in one figure and how to save them at good quality. Each example creates its own data and saves a PNG file, so you can run it anywhere.

What you need

  • Python 3.9+ with matplotlib, pandas and numpy (pip install matplotlib pandas).
  • In Jupyter, charts display automatically. In a script, call plt.show() to open a window, or save to a file as we do here.

Step 1: Understand figures and axes

Matplotlib has two ways of working: a quick “pyplot” style (plt.plot(...)) and an explicit object-oriented style. The explicit style is clearer and scales better to multi-chart figures, so we use it throughout:

Annotated line chart showing the parts of a Matplotlib figure: the Figure, the Axes plot area, the title, the line and the x-axis label, each with the method that sets it
The parts of a chart and the method that controls each one.
import matplotlib
matplotlib.use("Agg")   # file output only; remove this line in Jupyter
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot([1, 2, 3, 4], [10, 14, 12, 18])
ax.set_title("My first chart")
fig.savefig("first_chart.png", dpi=150, bbox_inches="tight")
plt.close(fig)

The figure is the whole image; an axes is one chart within it (with its own x-axis, y-axis and data). plt.subplots() creates both. You then call methods on ax to draw and label, and on fig to save. Closing figures you have finished with avoids memory warnings when you create many charts in a loop.

Step 2: Line charts for trends over time

Use a line chart when the x-axis is ordered, usually time:

Four small example charts: a line chart for a trend, a bar chart comparing categories, a histogram of a distribution and a scatter plot of a relationship
Pick the chart type from the question you are answering.
rng = np.random.default_rng(42)
months = pd.date_range("2024-01-01", periods=12, freq="MS")
online = 200 + np.arange(12) * 12 + rng.normal(0, 10, 12)
store = 260 - np.arange(12) * 4 + rng.normal(0, 10, 12)

fig, ax = plt.subplots(figsize=(9, 4.5))
ax.plot(months, online, marker="o", label="Online")
ax.plot(months, store, marker="o", label="Store")
ax.set_title("Online sales overtook store sales in spring 2024")
ax.set_ylabel("Revenue (£k)")
ax.legend(frameon=False)
ax.spines[["top", "right"]].set_visible(False)
ax.grid(axis="y", alpha=0.3)
fig.autofmt_xdate()
fig.savefig("line_chart.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Notice the title. Rather than describing the chart (“Sales by channel”), it states the finding. This is one of the most effective changes you can make: readers know immediately what to look for. (The data here is synthetic, so check that a headline title matches your own data before you use one.) Removing the top and right borders and using a light grid reduces clutter without losing information.

Step 3: Bar charts for comparing categories

Bar charts compare quantities across categories. Sort the bars so the ranking is obvious, and use horizontal bars when labels are long:

regions = pd.Series({"North East": 120, "London": 410, "Scotland": 180,
                     "South West": 220, "Wales": 95, "Midlands": 300})
regions = regions.sort_values()

fig, ax = plt.subplots(figsize=(7, 4))
bars = ax.barh(regions.index, regions.values, color="#4C72B0")
ax.bar_label(bars, padding=3, fmt="%d")
ax.set_xlabel("Orders")
ax.set_title("London generates the most orders")
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("bar_chart.png", dpi=150, bbox_inches="tight")
plt.close(fig)

bar_label writes the value on each bar, so readers do not have to estimate from the axis. Bar charts must start at zero: the length of the bar is the message, and a truncated axis exaggerates differences. Line charts, by contrast, can use a narrower range if it helps show change.

Step 4: Highlight what matters

Colour is most powerful when used sparingly. Grey out everything except the item you want to discuss:

colours = ["#C44E52" if r == "Wales" else "#BBBBBB" for r in regions.index]
fig, ax = plt.subplots(figsize=(7, 4))
ax.barh(regions.index, regions.values, color=colours)
ax.set_title("Wales has the fewest orders – a target for the next campaign")
ax.set_xlabel("Orders")
ax.spines[["top", "right"]].set_visible(False)
fig.savefig("highlight_chart.png", dpi=150, bbox_inches="tight")
plt.close(fig)

Step 5: Histograms for distributions

A histogram shows how values are spread: where most fall, how wide the spread is, and whether there are long tails or outliers. Averages alone hide all of this.

basket = rng.gamma(shape=2.0, scale=20.0, size=2000)

fig, ax = plt.subplots(figsize=(8, 4))
ax.hist(basket, bins=40, color="#55A868", edgecolor="white")
ax.axvline(np.median(basket), color="black", linestyle="--", label=f"Median £{np.median(basket):.0f}")
ax.axvline(basket.mean(), color="grey", linestyle=":", label=f"Mean £{basket.mean():.0f}")
ax.set_xlabel("Basket value (£)")
ax.set_ylabel("Number of orders")
ax.set_title("Most baskets are small; a long tail of large orders pulls the mean up")
ax.legend(frameon=False)
fig.savefig("histogram.png", dpi=150, bbox_inches="tight")
plt.close(fig)

With skewed data like this, the mean sits to the right of the median. Showing both lines makes that visible. Try different bins values: too few hides the shape; too many makes it noisy.

Step 6: Scatter plots for relationships

Use a scatter plot to see how two numeric variables relate:

ad_spend = rng.uniform(1, 20, 80)
sales = 5 + 2.2 * ad_spend + rng.normal(0, 4, 80)

fig, ax = plt.subplots(figsize=(6, 5))
ax.scatter(ad_spend, sales, alpha=0.6)
slope, intercept = np.polyfit(ad_spend, sales, 1)
xs = np.linspace(ad_spend.min(), ad_spend.max(), 50)
ax.plot(xs, intercept + slope * xs, color="black", linewidth=1)
ax.set_xlabel("Ad spend (£k)")
ax.set_ylabel("Sales (£k)")
ax.set_title(f"Each extra £1k of ad spend is associated with ~£{slope:.1f}k sales")
fig.savefig("scatter.png", dpi=150, bbox_inches="tight")
plt.close(fig)

alpha (transparency) helps when points overlap. The fitted line is a simple linear regression; for a fuller treatment, including why “associated with” is not the same as “causes”, see Linear Regression in Python.

Step 7: Several charts in one figure

fig, axes = plt.subplots(1, 2, figsize=(11, 4), sharey=False)
axes[0].plot(months, online, marker="o")
axes[0].set_title("Online revenue (£k)")
axes[1].hist(basket, bins=30, color="#8172B2")
axes[1].set_title("Basket value distribution")
for a in axes:
    a.spines[["top", "right"]].set_visible(False)
fig.suptitle("Q4 dashboard", fontsize=14)
fig.tight_layout()
fig.savefig("multi_chart.png", dpi=150, bbox_inches="tight")
plt.close(fig)

plt.subplots(rows, cols) returns an array of axes. tight_layout() stops titles and labels overlapping. Use sharey=True when charts show the same measure, so readers can compare heights directly.

Step 8: Plot straight from pandas

pandas has a .plot() method that calls Matplotlib for you, and you can pass an ax to keep full control:

df = pd.DataFrame({"Online": online, "Store": store}, index=months)
fig, ax = plt.subplots(figsize=(9, 4))
df.plot(ax=ax, marker="o")
ax.set_ylabel("Revenue (£k)")
ax.set_title("Channel revenue, 2024")
fig.savefig("pandas_plot.png", dpi=150, bbox_inches="tight")
plt.close(fig)

This is the quickest route from a groupby summary to a chart.

Step 9: Save charts properly

  • PNG with dpi=150 or higher for slides, documents and websites.
  • SVG or PDF for print or when you need to scale without blurring.
  • bbox_inches="tight" trims excess whitespace and prevents labels being cut off.
  • Set figsize to match where the chart will appear, rather than resizing it afterwards, so text stays legible.

Choosing the right chart

  • Change over time → line chart.
  • Compare categories → bar chart (sorted).
  • Distribution of one variable → histogram or box plot.
  • Relationship between two variables → scatter plot.
  • Parts of a whole → a bar chart is usually clearer than a pie chart; if you must use a pie, keep it to a few slices.

Common mistakes

  • Truncated y-axis on bar charts, which exaggerates differences.
  • Missing axis labels or units. “Revenue” in what – pounds, thousands, millions?
  • Too many colours or lines. More than four or five lines becomes unreadable; highlight one and grey the rest, or use small multiples.
  • Unsorted bars, forcing readers to work out the ranking.
  • Red/green colour pairs, which many colour-blind readers cannot distinguish. Use blue/orange or add labels.
  • Descriptive titles that state nothing. Say what the reader should notice.
  • Forgetting plt.close() in loops, leading to memory warnings.

FAQ

Should I use Matplotlib, seaborn or Plotly?

Matplotlib gives complete control and underpins seaborn. Seaborn adds convenient statistical charts with good defaults. Plotly produces interactive charts for web pages and dashboards. Learning Matplotlib first makes the others easier.

How do I format the axis as currency?

Use a formatter: from matplotlib.ticker import StrMethodFormatter then ax.yaxis.set_major_formatter(StrMethodFormatter("£{x:,.0f}")).

How do I change the overall style?

plt.style.use("ggplot") or other built-in styles listed in plt.style.available. Apply it before creating figures.

Why is my chart blank when saved?

You probably called plt.show() before savefig(); showing can clear the figure. Save first.

Next steps

Prepare data for charts with pandas groupby and Dates and Times in Pandas. For interactive dashboards without code, try Building Your First Power BI Dashboard.

LJ

About the author: Lucky Joseph

Lucky is a UK-based writer with a data science background who runs DataScienceWay. Every tutorial is tested before publication; if you spot something that no longer works, please get in touch.

More about DataScienceWay · Contact