# Working with Objects¶

As we have seen before, the subplots()- function actually returns two values. These are variables of a custom data type (a so-called class) defined by matplotlib. We call those variables objects hence the name of this programming style.

from matplotlib import pyplot

months = [
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
]

water_levels_2010 = [
5.77, 6.04, 6.52, 6.48, 6.54, 5.92,
5.64, 5.21, 5.01, 5.18, 5.45, 5.59
]

water_levels_2020 = [
5.48, 5.82, 6.31, 6.26, 6.09, 5.87,
5.72, 5.54, 5.22, 4.86, 5.12, 5.40
]

# Create a figure
figure = pyplot.figure()

# Add two subplots to that figure
(axes_upper, axes_lower) = figure.subplots(nrows=2, ncols=1)  # (1) (2)

axes_upper.set_title("Water level in 2010")  # (3)
axes_upper.plot(months, water_levels_2010)

axes_lower.set_title("Water level in 2022")
axes_lower.plot(months, water_levels_2020)

figure.show()


Explanations

1. Note how figure.subplots(…) only returns the newly created axes, while pyplot.subplots(…) returns a new figure and the axes. The pyplot functions tend to create missing elements implicitly, which makes them often more convenient.
2. If the left side of the assignment looks odd to you: This makes use of the destructuring behaviour of Python. You can find a nice explanation in this blog post.
3. Note that the names of the functions can differ between the OOP-style and the imperative style.