Using variable vs plt.method when graphing?

In the Sublime Limes Line Graph project in the Visualize Data with Python Skill Path, I am confused as when to use a variable, such as the ax1 and ax2 created, versus when to use the standard plt when calling methods.

For instance, we created ax1 = plt.subplot(1, 2, 1), then we have
ax1.plot(x_values, …)
plt.xlabel(“Month”)

why is one ax1.method and the other plt.method? How do I know when to use each?

There’s no strict rule. For the most part plt.something is some sort of wrapper around the actual matplotlib set-up which is object based. A standard plt.something operation normally attempts to deal with the current figure or axis object or simply creates a new one. If you’re entirely unfamiliar with object-oriented programming then it may be easier to stick with the wrappers until you’re more comfortable.

If you’re dealing with multiple plots or plots with multiple axes then you may find it easier to start handling references for each of these items separately, otherwise you must be very linear in your plot design and carefully keep track of what is considered the ‘current’ figure or axis. Bear in mind there’s not always a direct relation between the two methods of use, e.g. the use of ax.set_xlabel vs. plt.xlabel.

Personally I much prefer the object oriented style for the most part as I’ve found no strong reason to use the other. That’s not to say the wrappers aren’t helpful in places but a lot of options are either replicated or improved upon by using references to the objects themselves. For more complex plots e.g. multiple axes, mixed plots, interactive or animated examples you’ll probably find the object-oriented style significantly easier, if not essential, to work with.

The lessons unfortunately are a little inconsistent about when they use object references vs. wrapper functions so you basically have to follow whatever the lesson says.

1 Like