Seaborn Project Question 8

https://www.codecademy.com/paths/data-science/tracks/data-visualization/modules/dspath-seaborn/projects/world-cup-viz

Q8 tells us to copy and paste this code into the editor

f, ax = plt.subplots(fig_size=(12, 7))

What does it mean f, ax? This is the first time I’ve seen f, ax = _______

I’ve only seen ax = ______ in the previous exercises

There’s a few similar functions in the matplotlib pyplot module but the subplots function returns a reference for both a figure instance and an axis instance (will return an numpy object array of axis instances if you ask for multiple subplots). So for the given use it’s just a handy way to get references to both figure and axis instance in a single line (docs say it’s just a wrapper for the subplots method of a figure instance).

For the given example it’s just quicker and easier to write than some of the alternatives-

fig1, ax1 = plt.subplots()
# instead of...
fig2 = plt.figure()
ax2 = fig2.add_subplot()
2 Likes

I think I get it, so if we leave out f, and just write:

ax = ____ it will still work but we won’t have a reference to f?

I’m still a bit confused as to what a figure instance is and an axis instance is

No, you couldn’t just leave out f with that particular function, it returns two objects (ax would be a tuple of the two instead which would make things more confusing). I don’t know why you’d ever want to be without a reference to a figure instance but you could use a throwaway name instead, e.g. -
_, ax = plt.subplots() but unless you had an unusually cluttered namespace it seems like an odd thing to do.

If you’ve not learnt much about classes yet much then a lot of matplotlib will be difficult to wrap your head around for a while. Worth looking up in the future.

For what I hope is a simpler explanation: every time you make a new figure or a new axis it creates a new object. Having references to these objects makes it easier to alter them, e.g. adding setting the x-axis label- ax.set_xlabel(‘example’).

You could create the figure and axis the way you already know how but you may as well lern some new functions on the way. I’d say using the subplots function is very common so at least know what it returns.

4 Likes

Thanks for this explanation.

For me, part the confusion lay in the fact that the Seaborn lessons have only introduced us to plt.subplot() which returns a single object - axes, whereas this is plt.subplots() which returns tow objects - a figure and a set of axes - which we then unpack.

(I’m writing that out in case anyone else was thrown for the same reason as me.)

1 Like