Changing pointplot legend in seaborn - python

I would like to change the label for the legend and items in the legend for this plot. Right now the label for the legend is "Heart" and the items are 0 and 1. I would like to be able to change all of these to something else, but am unsure how. Here is what I have so far.
sns.set_context("talk",font_scale=3)
ax =sns.pointplot(x="Heart", y="FirstPersonPronouns", hue="Speech", data=df)
ax.set(xlabel='Condition', ylabel='First Person Pronouns')
ax.set(xticklabels=["Control", "Heart"])
Any help would be appreciated! Also, I'm assuming this is a set parameter that I don't know about, is there a comprehensive list of these? I can't seem to find one in the documentation.

An alternative to changing the column names of the data frame, is to create a new legend using the same legend handles (this is what determines the colored markers), but with new text labels:
import seaborn as sns
tips = sns.load_dataset('tips')
ax = sns.pointplot(x='sex', y='total_bill', hue='time', data=tips)
leg_handles = ax.get_legend_handles_labels()[0]
ax.legend(leg_handles, ['Blue', 'Orange'], title='New legend')

Related

How to remove a legend part of a seaborn facetgrid

In Matplotlib/seaborn I create a facetgrid with the relplot command where the data attribute use for therow parameter is also used for the style attribute. This leads to a legend with two parts. One part is redundant and I want to remove this redundant part of the legend.
Here the code:
df = pd.read_csv('data.csv')
# Dataframe df has columns 'size', 'pricepersize', 'date' and 'series'
g = sns.relplot(x='size',
y='pricepersize',
data=df,
kind='line',
hue='date',
style='series',
row='series',
markers=True
)
plt.show()
And here the resulting graph grid (with the part of the legend I want to remove marked up in green):
How can I get rid of the "series" part in the legend, but keep the style parameter set to the same data column as the row parameter?
I guess the easiest way is to let sns create the legend (this is the default), remove it and re-generate a new one from the desired entries of the original legend.
import seaborn as sns
tips = sns.load_dataset("tips")
fg = sns.relplot(data=tips, x="total_bill", y="tip", hue="day", row="time", kind='line', style='time')
gives
then use
fg.legend.remove()
fg.fig.legend(handles=fg.legend.legendHandles[:5], loc=7)
to finally get

Overriding Seaborn legend

I made a line plot using seaborn's relplot and I wanted to customize my legend labels. For some reason when I do this, It creates another legend with out deleting the old one. How do I get rid of the initial legend (The legend with title "Sex")? Also how do I add a legend title to my new legend?
Here is the code I used to generate my plot:
plt.figure(figsize=(12,10))
sns.relplot(x='Year',y = 'cancer/100k pop' , data = dataset_sex,hue="Sex", kind="line",ci=None)
title_string = "Trend of Cancer incidencies by Sex "
plt.xlabel('Years')
plt.title(title_string)
plt.legend(['Men','Women'])
regplot is a figure-level function, and returns a FacetGrid. You can remove its legend via g.legend.remove().
import matplotlib.pyplot as plt
import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.relplot(data=tips, x="total_bill", y="tip", hue="day")
g.legend.remove()
plt.legend(['Jeudi', 'Vendredi', 'Samedi', 'Dimanche'])
plt.show()
This code has been tested with seaborn 0.11. Possibly you'll need to upgrade. To add a title to the legend: plt.legend([...], title='New title').
Note that plt.legend(...) will create the legend inside the last (or only) subplot. If you prefer the figure-level legend next to the plot, to change the legend labels, you can call g.add_legend(labels=[...], title='new title') after having removed the old legend.
PS: Adding legend=False to sns.relplot() will not create the legend entries. So, you'll need to recreate both the legend markers and their labels, while you lost the information of which colors were used.

remove legend handles and labels completely

Some plotting tools such as seaborn automatically label plots and add a legend. Removing the legend is fairly easy with ax.get_legend().remove(), but the handles and labels are still stored somewhere in the axes object. Thus when adding another line or other plot type, for which I want to have a legend, the "old" legend handles and labels are also displayed. In other words: ax.get_legend_handles_labels() still returns the labels and handles introduced by f.i. seaborn.
Is there any way to completely remove the handles and labels to be used for a legend from an axis?
Such that ax.get_legend_handles_labels() returns ([], [])?
I know that I can set sns.lineplot(..., legend=False) in seaborn. I am just using seaborn to produce a nice example. The question is how to remove existing legend labels and handles in general.
Here is a minimum working example:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
df = pd.DataFrame(data={
'x': [0, 1, 0, 1],
'y': [7.2, 10., 11.2, 3.],
'id': [4, 4, 7, 7]
})
# get mean per x location:
grpd = df.groupby('x').mean()
ax = sns.lineplot(data=df, x='x', y='y', hue='id', palette=['b', 'g'])
ax.get_legend().remove()
# this still returns the handles and labels:
print(ax.get_legend_handles_labels())
# Out:
# ([<matplotlib.lines.Line2D at 0x17c1c208f88>,
# <matplotlib.lines.Line2D at 0x17c1c1f8888>,
# <matplotlib.lines.Line2D at 0x17c1c20af88>],
# ['id', '4', '7'])
# plot some other lines, for which I want to have a legend:
ax.plot(grpd.index, grpd['y'], label='mean')
# add legend, ONLY FOR MEAN, if possible:
ax.legend()
I tried manipulating the axes ax.get_legend() and ax.legend_ objects, f.i. with ax.legend_.legendHandles = [], setting the labels, texts and everything else, but the "old" seaborn entries keep reappiering each time.
Since this is meant to be used within a module, it is no applicable to explicitly set a legend only containing the "mean"-entry. I need to "clear" everything happening in the backend to provide a clean API to the user.
Change:
ax = sns.lineplot(data=df, x='x', y='y', hue='id', palette=['b', 'g'])
to:
ax = sns.lineplot(data=df, x='x', y='y', hue='id', palette=['b', 'g'], legend=False)
That way you also don't need to make the call to remove the legend as none is created in the first place.
EDIT UPDATE:
If you want to clear the legend handles and label, I think you'll have to do something like:
for line in ax.lines: # put this before you call the 'mean' plot function.
line.set_label(s='')
This will loop over the lines draw on the plot and then set their label to be empty. That way the legend doesn't consider them and the print(ax.get_legend_handles_labels()) will return empty iterables.
Thanks at mullinscr for the answer considering line plots. To remove legend labels in general, the labels of lines, collections (f.i. scatter plots), patches (boxplots etc) and images (imshow etc.) must be cleared:
for _artist in ax.lines + ax.collections + ax.patches + ax.images:
_artist.set_label(s=None)
Please tell me, if I forgot to mention a specific kind of plot.
Another option is to do the following:
ax.legend(handles=[], labels= [])
In this case, everything will be removed.
If for example you would like to only remove the first handle, you can do the following:
fetch the handles and labels of your plot:
h, l = ax.get_legend_handles_labels()*
select the ones you want (here all except the first):
ax.legend(handles=[item for item in h[1:], labels= [item for item in l[1:])
This way, you can sort out the things you want.

Seaborn clustermap legend overlap with figure

'''
Hi there,
I created a clustermap using seaborn. Because the legend overlaps with the figure, I'd like to move it. However, plt.legend(bbox_to_anchor=(1,1)) gave the following error 'No handles with labels found to put in legend.'
That makes me wonder: what is the color scale -20 to 20 on the top left that I want to re-position? isn't that a legend?
Thank you in advance for shedding light on that for me.
'''
import matplotlib.pyplot as plt
import seaborn as sns
g = sns.clustermap(data=df_highestPivot,cmap='coolwarm')
plt.legend(bbox_to_anchor=(1,1)) #This line generate the error
plt.savefig('plot.png',dpi=300,bbox_to_inches='tight')
plt.show()
plt.close()
The colorbar is not a legend per se (not an object of type Legend at least). It is actually it's own subplots Axes, that you can access using g.ax_cbar.
If you want to move it, you can pass an argument cbar_pos= to clustermap(). However, it's complicated to find an empty space in the figure to place it. I would recommend you make some room using subplots_adjust() then move the ax_cbar Axes at the desired location
iris = sns.load_dataset('iris')
species = iris.pop("species")
g = sns.clustermap(iris)
g.fig.subplots_adjust(right=0.7)
g.ax_cbar.set_position((0.8, .2, .03, .4))

Edit legend title and labels of Seaborn scatterplot and countplot

I am using seaborn scatterplot and countplot on titanic dataset.
Here is my code to draw scatter plot. I also tried to edit legend label.
ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_handles, _ = ax.get_legend_handles_labels()
plt.show();
To edit legend label, I did this. In this case, there is no legend title anymore. How can I rename this title from 'who' to 'who1'?
ax = seaborn.countplot(x='class', hue='who', data=titanic)
legend_handles, _= ax.get_legend_handles_labels()
ax.legend(legend_handles, ['man1','woman1','child1'], bbox_to_anchor=(1,1))
plt.show()
I used the same method to edit legend labels on scatter plot and the result is different here. It uses 'dead' as legend title and use 'survived' as first legend label.
ax = seaborn.scatterplot(x='age', y='fare', data=titanic, hue = 'survived')
legend_handles, _= ax.get_legend_handles_labels()
ax.legend(legend_handles, ['dead', 'survived'],bbox_to_anchor=(1.26,1))
plt.show()
Is there a parameter to delete and add legend title?
I used same codes on two different graphs and outcome of legend is different. Why is that?
Try using
ax.legend(legend_handles, ['man1','woman1','child1'],
bbox_to_anchor=(1,1),
title='whatever title you want to use')
With seaborn v0.11.2 or later, use the move_legend() function.
From the FAQs page:
With seaborn v0.11.2 or later, use the move_legend() function.
On older versions, a common pattern was to call ax.legend(loc=...) after plotting. While this appears to move the legend, it actually replaces it with a new one, using any labeled artists that happen to be attached to the axes. This does not consistently work across plot types. And it does not propagate the legend title or positioning tweaks that are used to format a multi-variable legend.
The move_legend() function is actually more powerful than its name suggests, and it can also be used to modify other legend parameters (font size, handle length, etc.) after plotting.
Why does the legend order sometimes differ?
You can force the order of the legend via hue_order=['man', 'woman', 'child']. By default, the order is either the order in which they appear in the dataframe (when the values are just strings), or the order imposed by pd.Categorical.
How to rename the legend entries
The surest way is to rename the column values, e.g.
titanic["who"] = titanic["who"].map({'man': 'Man1', 'woman': 'Woman1', 'child': 'Child1'})
If the entries of the column exist of numbers in the range 0,1,..., you can use pd.Categorical.from_codes(...). This also forces an order.
Specific colors for specific hue values
There are many options to specify the colors to be used (via palette=). To assign a specific color to a specific hue value, the palette can be a dictionary, e.g.
palette = {'Man1': 'cornflowerblue', 'Woman1': 'fuchsia', 'Child1': 'limegreen'}
Renaming or removing the legend title
sns.move_legend(ax, title=..., loc='best') sets a new title. Setting the title to an empty string removes it (this is useful when the entries are self-explaining).
A code example
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
titanic = sns.load_dataset('titanic')
# titanic['survived'] = titanic['survived'].map({0:'Dead', 1:'Survived'})
titanic['survived'] = pd.Categorical.from_codes(titanic['survived'], ['Dead', 'Survived'])
palette = {'Dead': 'navy', 'Survived': 'turquoise'}
ax = sns.scatterplot(data=titanic, x='age', y='fare', hue='survived', palette=palette)
sns.move_legend(ax, title='', loc='best') # remove the title
plt.show()

Categories