For python relplot, how to control the location of legend and add a plot title? I tried plt.title('title')
but it doesn't work.
import seaborn as sns
dots = sns.load_dataset("dots")
# Plot the lines on two facets
sns.relplot(x="time", y="firing_rate",
hue="coherence", size="choice", col="align",
size_order=["T1", "T2"],
height=5, aspect=.75, facet_kws=dict(sharex=False),
kind="line", legend="full", data=dots)
To change the position of a legend in a seaborn plot, you can use the plt. legend() command. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.
By default, seaborn automatically adds a legend to the graph. Notice the legend is at the top right corner. If we want to explicitly add a legend, we can use the legend() function from the matplotlib library.
You can use the bbox_to_anchor() argument to place a seaborn legend outside of the plot. Note that the (1.05, 1) coordinates correspond to the (x, y) coordinates where the legend should be placed and the borderaxespad specifies the padding between the axes and the border legend.
A typical way of changing the location of a legend in matplotlib is to use the arguments loc
and bbox_to_anchor
.
In Seaborn's relplot
a FacetGrid object is returned. In order to get the legend object we can use _legend
. We can then set the loc
and bbox_to_anchor
:
g = sns.relplot(...)
leg = g._legend
leg.set_bbox_to_anchor([0.5, 0.5]) # coordinates of lower left of bounding box
leg._loc = 2 # if required you can set the loc
To understand the arguments of bbox_to_anchor
see What does a 4-element tuple argument for 'bbox_to_anchor' mean in matplotlib?
The same can be applied to the title. The matplotlib argument is suptitle
. But we need the figure object. So we can use
g.fig.suptitle("My Title")
Putting this all together:
import seaborn as sns
dots = sns.load_dataset("dots")
# Plot the lines on two facets
g = sns.relplot(x="time", y="firing_rate",
hue="coherence", size="choice", col="align",
size_order=["T1", "T2"],
height=5, aspect=.75, facet_kws=dict(sharex=False),
kind="line", legend="full", data=dots)
g.fig.suptitle("My Title")
leg = g._legend
leg.set_bbox_to_anchor([1,0.7]) # change the values here to move the legend box
# I am not using loc in this example
Update
You can change the position of the title by providing the x and y coordinates (figure coordinates) so that it doesn't overlap the subplot titles
g.fig.suptitle("My Title", x=0.4, y=0.98)
Although I would probably move your subplots down slightly and leave the figure title where it is using:
plt.subplots_adjust(top=0.85)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With