Matplotlib: Figure, Axes and Your First Chart

First lesson of the Visualization (Matplotlib, Seaborn, Plotly) course, free to read: about 15 minutes, 3 exercises and 3 quiz questions. This is the catalogue's base lesson; in the student space, it is rewritten for your profile.

Objectives

  • Create a figure and axes with the object-oriented interface
  • Plot one or more lines with a title, axis labels and a legend
  • Save a chart to an image file

Figure and AxesLinesTitles, labels and legend

Matplotlib: Figure, Axes and Your First Chart

Matplotlib is Python’s original visualization library. Seaborn and pandas use it behind the scenes: understanding how it works will help you everywhere.

Figure and Axes

A Matplotlib chart is organized on two levels:

  • the Figure (Figure): the “sheet” that contains everything;
  • one or more Axes (Axes): plotting areas, each with its own x axis, y axis and title.
import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(8, 4))   # an 8 x 4 inch figure, a single Axes

You then draw by calling the methods of ax. This is the object-oriented interface, which is the recommended one. There is a shorter interface (plt.plot(...), plt.title(...)) that acts on the “current axes”: handy for a quick test, but confusing as soon as there are several charts.

A first line

mois = ["janv", "févr", "mars", "avr", "mai", "juin"]
ca_2025 = [120, 135, 128, 150, 162, 170]
ca_2026 = [130, 142, 155, 149, 175, 190]

fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(mois, ca_2025, marker="o", label="2025")            # one series
ax.plot(mois, ca_2026, marker="o", linestyle="--", label="2026")  # a second one

ax.set_title("Monthly revenue")               # title
ax.set_xlabel("Month")                        # x axis label
ax.set_ylabel("Revenue (k€)")                 # with the unit!
ax.legend()                                   # shows the labels
ax.grid(alpha=0.3)                            # subtle grid
plt.show()                                    # in a notebook, display is automatic

Each call to ax.plot adds a line (Line2D) to the Axes. The label parameter gives its name in the legend, which only appears if you call ax.legend().

Style

The most useful parameters of plot:

Parameter Examples Effect
color "tab:blue", "#1f77b4" color
marker "o", "s", "^" symbol on each point
linestyle "-", "--", ":" line type
linewidth 2 thickness

ax.set_ylim(0, None) forces the y axis to start at zero, which avoids visually exaggerating variations. ax.set(title=..., xlabel=..., ylabel=...) sets several properties at once.

A line connects the points: it suggests continuity. Reserve it for ordered data, typically time. To compare categories (regions, products), use bars (next lesson).

Saving

fig.savefig("ca_mensuel.png", dpi=150, bbox_inches="tight")
plt.close(fig)   # frees memory when you generate many figures

bbox_inches="tight" trims unnecessary margins; the format is inferred from the extension (.png, .svg, .pdf).

Checking a chart with code

Matplotlib objects can be queried, which makes it possible to test a chart:

ax.get_title()            # "Monthly revenue"
len(ax.get_lines())       # 2 lines
[t.get_text() for t in ax.get_legend().get_texts()]   # ['2025', '2026']

This is how the exercises in this course check your charts.

Key takeaways

  • fig, ax = plt.subplots() then ax.* methods.
  • Title, labels with units, legend: always.
  • Line for time; savefig to export.

Exercises

Solutions and tests stay on the server. In the student space, your code is run and checked, and the tutor gives hints before the solution.

  1. CodeDifficulty 1Python in the browser2 hints

    Annotated line

    Create a figure fig and an axes ax with plt.subplots(). Plot ventes against jours with round markers and the label “Ventes”. Add the title “Ventes de la semaine”, the labels “Jour” and “Ventes (unités)”, and the legend.

    import matplotlib.pyplot as plt
    
    jours = ["lun", "mar", "mer", "jeu", "ven"]
    ventes = [12, 18, 9, 22, 30]
    
    fig, ax = ...
  2. CodeDifficulty 2Python in the browser2 hints

    Compare two series and export

    On a single axes, plot the series objectif (dashed line "--", label “Objectif”) and realise (label “Réalisé”). Title “Objectif vs réalisé”, y axis starting at 0 (set_ylim(0, None)), legend. Then save the figure in PNG format into an io.BytesIO object named buffer (fig.savefig(buffer, format="png")).

    import io
    import matplotlib.pyplot as plt
    
    mois = ["janv", "févr", "mars", "avr"]
    objectif = [100, 110, 120, 130]
    realise = [95, 118, 112, 141]
    
    fig, ax = plt.subplots()
    ...
    buffer = io.BytesIO()
  3. Multiple choiceDifficulty 11 hint

    Figure or Axes

    In fig, ax = plt.subplots(), which object carries the chart title with set_title?

    • fig
    • ax
    • plt
    • Either one

End-of-lesson quiz

  1. What does fig, ax = plt.subplots() create?

    • Two figures
    • A figure containing a single Axes
    • A figure with no axes
  2. Why does the legend not appear despite label="2026"?

    • The label is too short
    • ax.legend() was not called
    • You need at least two lines
  3. For which data is a line (plot) most suitable?

    • A trend over time
    • A breakdown across 3 regions
    • An unordered list of products

The rest of the course

  1. Choosing the Right Chart: Bars, Histograms, Scatter Plots20 min
  2. Subplots, Formatting and Annotations20 min
  3. Seaborn: Statistical Charts from a DataFrame20 min
  4. Plotly: Interactive Charts20 min

Visualization (Matplotlib, Seaborn, Plotly) · Intermediate · 3 h 5 min