2

I have created a simple violin plot from a bands DataFrame (df10 below) using seaborn:

fig, ax = plt.subplots(figsize=(10,4))
ax = sns.violinplot(x='z', y='z_fit', hue='new_col', data=df10, cut=0, palette='Blues', linewidth=1)
ax.set_xlabel('z_sim')
ax.legend()

The legend is plotted automatically with the values of the hue parameter. Using ax.legend() I can only hide the name of the used column ('new_col').

However, I was wondering if there is some way to manually modify the legend (texts, colors and shapes) plotted below: enter image description here

Alessandro Peca
  • 873
  • 1
  • 15
  • 40
  • I think you forgot you say what you want to modify (The answer to if it is possible is clearly "yes"). Colors? Texts? Shapes? – ImportanceOfBeingErnest Apr 21 '19 at 16:57
  • All of those you have mentioned. But the most important thing is the text. – Alessandro Peca Apr 21 '19 at 17:00
  • 1
    So I think the purpose of SO answers is not to give a complete tutorial about legends; but fortunately there is such [legend tutorial](https://matplotlib.org/tutorials/intermediate/legend_guide.html) in the matplotlib documentation. Concerning the text labels, it should be enough to set `labels=["label1", "label2"]`, at the risk of not being a general solution. (The general case would require to preset `hue_order` in the seaborn call; or to just name the entries in the dataframe column as desired to begin with.) – ImportanceOfBeingErnest Apr 21 '19 at 17:11
  • https://stackoverflow.com/questions/45201514/edit-seaborn-legend – Tom Ron Apr 21 '19 at 17:11

1 Answers1

0

Example:

import seaborn as sns
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col="time", size=4, aspect=.75)
g = g.map(sns.violinplot, "sex", "total_bill", "smoker", palette={"No": "b", "Yes": "w"}, inner=None, linewidth=1, scale="area", split=True, width=0.75).despine(left=True)
g.fig.get_axes()[0].legend(title= 'smoker',loc='top left',labels=["YES","NO"],edgecolor='red',facecolor='blue',ncol=2)
g.set_axis_labels('lunch','total bill')

For more info run:

help(g.fig.get_axes()[0].legend)
Ayman
  • 51
  • 5