In matplotlib and seaborn how to move the legend outside of the figure?
- User
In matplotlib and seaborn how to move the legend outside of the figure?
- Assistant
You can move the legend outside of the figure in matplotlib and seaborn by using the loc parameter and adjusting the figure size. Here are a few ways to do it: Method 1: Using loc parameter You can use the loc parameter to specify the location of the legend outside the figure. For example, to place the legend to the right of the figure, you can use loc='upper right' and adjust the figure size using bbox_to_anchor: import matplotlib.pyplot as plt import seaborn as sns
Create a sample plot
sns.set() tips = sns.load_dataset("tips") fig, ax = plt.subplots(figsize=(8, 6)) sns.scatterplot(x="total_bill", y="tip", data=tips, ax=ax)
Move the legend outside the figure
ax.legend(loc='upper right', bbox_to_anchor=(1.05, 1))
plt.show() CopiedThis will place the legend to the right of the figure. Method 2: Using bbox_to_anchor and loc You can also use bbox_to_anchor to specify the location of the legend outside the figure, and loc to specify the alignment of the legend. For example: import matplotlib.pyplot as plt import seaborn as sns
Create a sample plot
sns.set() tips = sns.load_dataset("tips") fig, ax = plt.subplots(figsize=(8, Copied
- User
No, this is still inside the figure, how to move it out of the figure (with the default figure size)
- Assistant
To move the legend outside the figure, you can use the bbox_to_anchor parameter and set the loc parameter to a value that places the legend outside the figure. Additionally, you need to adjust the figure size using the figsize parameter to make room for the legend. Here's an example: import matplotlib.pyplot as plt import seaborn as sns
Create a sample plot
sns.set() tips = sns.load_dataset("tips") fig, ax = plt.subplots(figsize=(6, 4)) # default figure size sns.scatterplot(x="total_bill", y="tip", data=tips, ax=ax)
Move the legend outside the figure
ax.legend(loc='center left', bbox_to_anchor=(1.05, 0.5))
plt.tight_layout(rect=[0, 0, 0.8, 1]) # adjust the layout to make room for the legend
plt.show() CopiedIn this example, the bbox_to_anchor parameter is set to (1.05, 0.5), which places the legend to the right of the figure, outside the plot area. The loc parameter is set to 'center left' to align the legend with the center of the plot. The tight_layout function is used to adjust the layout of the figure to make room for the legend. The rect parameter is set to [0, 0, 0.8, 1], which means that the plot area will take up 80% of the figure width, leaving 20% for the legend. This should move the legend outside the figure, while keeping the default figure size.