Reputation: 583
I'm trying to plot a swarmplot with seaborn but I'm struggling with the legend of the plot, I managed to change its position if the figure, but now it is cropped and no information is shown:
I moved the legend with:
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
I changed the size of the figure with no luck
plt.figure(figsize=(12, 10))
I also tried tight_layout()
but it just removes the legend from the plot.
Any ideas on how to make it appear on the side of the plot nicely without any cropping on the side or bottom?
Thank you
Upvotes: 0
Views: 4855
Reputation: 146
You can do that like this.
# Import necessary libraries
import seaborn as sns
import matplotlib.pyplot as plt
# Initialize Figure and Axes object
fig, ax = plt.subplots(figsize=(10,4))
# Load in the data
iris = sns.load_dataset("iris")
# Create swarmplot
sns.swarmplot(x="species", y="petal_length", data=iris, ax=ax)
# Show plot
plt.show()
(its too late maybe i know but i wanted to share i found already)
Upvotes: 1
Reputation: 339580
The legend is not taken into account when plt.tight_layout()
tries to optimize the spaces. However you can set the spaces manually using
plt.subplots_adjust()
The relevant argument here is the right
side of the figure, so plt.subplots_adjust(right=0.7)
would be a good start. 0.7
means that the right part of the axes is at 70% of the total figure size, which should give you enough space for the legend.
Then, you may want to change that number according to your needs.
Upvotes: 3