Matplotlib - Requirement for calling axis each time

Does creating a chart legend using Matplotlib in Python requires a call for axis i.e. ax=plt.subplot() each time or the legend can be created without calling for ax=plt.subsplot()?
Also, what is the rationale behind it?

I tried using plt.legend / ax.plt.legend(’’,’’) to introduce legends in the chart but it didn’t work.

Refer to the site/code below:
https://www.codecademy.com/paths/data-science/tracks/data-visualization/modules/dspath-matplotlib/lessons/matplotlib-ii/exercises/stacked-bars

The use of plt.subplot() is really supposed to be a method to create a new axis subplot so if you’re using it, make sure to do so at the start to ensure any additional commands plot to the correct axis (it now has a deprecation warning for this behaviour too).

plt.legend would technically work if you’re using just a single axis. It does require a sequence of labels though, e.g. plt.legend(["data1", "data2"]), ideally at the same length as what you are creating a legend for (for basic options the rest is automated anyway).

Something to consider: using figure/axis references and their methods...

Peronsally I’d encourage you to get used to using the axis reference though “ax” or whatever name you provided it. For more complex plots, relying on standard pyplot functions can result in a bit of a headache. Even MATLAB which matplotlib generally emulates seemed to wind up using objects for this.

It’s up to you to use this style if you wish and you can get away with the pyplot wrapper functions for a lot of things (though references to invidual figures and axes is still very important so keep them either way) but here’s how the plotting for your given example might look-

fig, ax = plt.subplots(1, 1)
ax.bar(store1_x, sales1)
ax.bar(store2_x, sales2)
ax.set_title('Sales of drink at 2 store locations by types')
ax.set_xlabel('Drinks')
ax.set_ylabel('Sales')
ax.legend(("data1", "data2"))
fig.show()
1 Like

Thanks, this is helpful. Till now, have used ax = plt.subplot(a,b,c).
Will try it (fig, ax) and deploy axis for creating attributes of the charts such as legend, labels, etc.

1 Like

I’ve always found plt.subplots to be easier (mostly because it’s quicker to write) and gridspec when a more complex subplot set-up was required, but the other routes are just as valid. Maintaing a reference to those figure/axis objects is always a good idea though (this extends further to the plots themselves, e.g. bar1 = ax1.bar() etc. etc.).

I think it’s worthwhile learning because I personally found working with multiple figures and axes to be a nightmare if you try to do it the other way around and doubly so if you ever try updating plots on the fly such as creating multiple similar images or making animations.

1 Like