- I am a beginner in Python doing an online course. The following is an abstracted version of a given solution in the course.
- In one exercise a
seabornplot is generated and alegendis added. - Issue: I do not understand how the legend is on the right side based on the parameters that are used. How is
loc = 'center left'placing thelegendon the right side of the plot? - The
(https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html)
CodePudding user response:
The interpretation of
locchanges unintuitively when you also pass a coordinate argument forbbox_to_anchor. When both are present, thelocof the legend box is anchored on thebbox_to_anchorcoordinate.So what you have done is asked it to align the legend such that the box is left-aligned and vertically-centered on the (1, .5) coordinate of the axes, which puts it outside of the plot to the right.
To put it where you expect, you could do
loc="center left", bbox_to_anchor=(0, .5). Or just don't setbbox_to_anchor, which is only really relevant when you want to fine-tune the position beyond the 9 points you can spell out inloc. E.g., if you want the legend in the lower right-hand of the axes, but padded a bit from the corner, you could doloc="lower right", bbox_to_anchor=(.85, .15).CodePudding user response:
I believe it is due to the difference between a figure and an axis.
Matplotlib has two objects: figures and axes. A figure is the overall plot that matplotlib is drawing and axes are the individual axes for plotting something. For example, you may have a figure with four axes for four individual subplots.
You can work without axes e.g.
plt.plot(x,y)or with axes e.g.
fig, ax = plt.subplots(1,1) ax.plot(x,y)I believe (and would love for someone more experienced to delve deeper into this distinction) it is generally better to work with axes as it gives you more control as you create more complex figures.
So, what does this have to do with Seaborn? Well, I am pretty sure that Seaborn always works with axes. What this means is that
plt.legendis drawing a legend on the last used axes and NOT on the specific axis that Seaborn drew. As a result, the normal placement options don't work.What you can do instead is to create a variable to get the axis created by Seaborn so you can draw the legend on that axis:
ax = sb.barplot(data = df, x = 'Name', y = 'Age', hue = 'Gender') ax.legend(loc = 'center left', bbox_to_anchor = (1, 0.5))Alternatively, you can define the axis prior to plotting.
fig, ax = plt.subplots(1,1) sb.barplot(data = df, x = 'Name', y = 'Age', hue = 'Gender', ax=ax) ax.legend(loc = 'center left', bbox_to_anchor = (1, 0.5))

