2

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_labels, _= ax.get_legend_handles_labels()
pyplot.show();

output

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_labels, _= ax.get_legend_handles_labels()
ax.legend(legend_labels, ['man1','woman1','child1'], bbox_to_anchor=(1,1))
pyplot.show();

output2

I used the same method to edit legend labels on scatter plot and result is different here. It uses 'dead' as legend title and use 'survied' as first legend label.

ax = seaborn.scatterplot(x='age', y='fare', data=titanic, hue = 'survived')
legend_labels, _= ax.get_legend_handles_labels()
ax.legend(legend_labels, ['dead', 'survived'],bbox_to_anchor=(1.26,1))
pyplot.show();

enter image description here

(1) Is there a parameter to delete and add legend title?

(2) I used same codes on two different graphs and outcome of legend is different. Why is it?

Thank you

Dohun
  • 349
  • 1
  • 4
  • 11
  • 4
    The legend title is set via `ax.get_legend().set_title("bla")`. In the case of a seaborn scatterplot what *appears* to be the title is just another label without corresponding handle. In that case refer to https://stackoverflow.com/a/51579663/4124317 – ImportanceOfBeingErnest Feb 22 '20 at 13:11

1 Answers1

7

Try using

ax.legend(legend_labels, ['man1','woman1','child1'], 
          bbox_to_anchor=(1,1), 
          title='whatever title you want to use')
Ahmad Javed
  • 464
  • 5
  • 19