Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change legend location and labels in Seaborn scatter plot

I am tying to change the location as well as labels of my legend in Seaborn scatterplot. Here is my code:

ax_total_message_ratio=sns.scatterplot(x='total_messages', y='email_messages_ratio',hue='poi',data=df_new)
ax_total_message_ratio.set_title("Email Messages Ratio vs. Total Messages Across Poi",y=1.12,fontsize=20,fontweight='bold')
ax_total_message_ratio.set_ylabel('Email Messages Ratio')
ax_total_message_ratio.set_xlabel('Total Messages')
ax_total_message_ratio.legend.loc("lower right")
put.show()

enter image description here But I am getting following error message; 'function' object has no attribute 'loc'. Can I get some help on how to control legends with Seaborn? Additionally, I also need to replace 0 by No and 1 by Yes in the legend labels. Thanks

like image 442
jay Avatar asked Feb 14 '19 02:02

jay


People also ask

How do I change my legend location in Seaborn?

Changing the location of Seaborn legends We use matplotlib. pyplot. legend() function from matplotlib library and pass the bbox_to_anchor parameter which allows us to pass an (x,y) tuple with the required offset for changing the location of the seaborn legends.

How do you change markers in Seaborn scatter plot?

Changing Marker Color on a Scatter Plot You can change the color of a scatter plot by first passing the letter of the color name to the color parameter of the scatterplot() function.

How do you move the legend in Seaborn Boxplot?

With Seaborn's move_legend() function, we can easily change the position to common legend places. For example, to move the legend to lower right of Seaborn plot we specify “lower right” to move_legend() function. Note now the legend is moved to the lower left corner of the plot.


2 Answers

You can adjust the position using the loc keyword in calling legend(), like

ax_total_message_ratio.legend(loc="lower right")

To include custom labels for your markers you can create a custom legend, i.e.

import matplotlib.pyplot as plt
from matplotlib.lines import Line2D

custom = [Line2D([], [], marker='.', color='b', linestyle='None'),
          Line2D([], [], marker='.', color='r', linestyle='None')]

fig = plt.figure(figsize=(8,5))

plt.legend(custom, ['Yes', 'No'], loc='lower right')
plt.show()

This will give you

Sample plot with custom legend

and should remove the automatically generated legend, leaving only the custom legend.

like image 177
William Miller Avatar answered Sep 17 '22 19:09

William Miller


You can use the convenience method get_legend_handles_labels() to get the handles and the text of the labels:

ax=sns.scatterplot(x='total_messages', y='email_messages_ratio',hue='poi',data=df_new)

handles, labels  =  ax.get_legend_handles_labels()

ax.legend(handles, ['Yes', 'No'], loc='lower right')
like image 43
fotis j Avatar answered Sep 18 '22 19:09

fotis j