Issue
- 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
seaborn
plot is generated and alegend
is 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 thelegend
on the right side of the plot? - The
matplotlib
manual says:
The strings 'upper center', 'lower center', 'center left', 'center right' place the legend at the center of the corresponding edge of the axes/figure.
- I am sure that there is a logical answer but I am not able to see it :).
Code Listing
import pandas as pd
import seaborn as sb
# https://www.geeksforgeeks.org/different-ways-to-create-pandas-dataframe/
# initialize data of lists.
data = {'Name':['Tim', 'Tom', 'Cindy', 'Mandy'],
'Age':[20, 21, 19, 18],
'Gender':['Male', 'Male', 'Female', 'Female']}
# Create DataFrame
df = pd.DataFrame(data)
sb.barplot(data = df, x = 'Name', y = 'Age', hue = 'Gender')
plt.legend(loc = 'center left', bbox_to_anchor = (1, 0.5)) # legend to right of figure
Screenshots
(https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.legend.html)
Solution
The interpretation of loc
changes unintuitively when you also pass a coordinate argument for bbox_to_anchor
. When both are present, the loc
of the legend box is anchored on the bbox_to_anchor
coordinate.
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 set bbox_to_anchor
, which is only really relevant when you want to fine-tune the position beyond the 9 points you can spell out in loc
. E.g., if you want the legend in the lower right-hand of the axes, but padded a bit from the corner, you could do loc="lower right", bbox_to_anchor=(.85, .15)
.
Answered By - mwaskom
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.