Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit a seaborn legend title and labels for figure-level functions

I've created this plot using Seaborn and a pandas dataframe (data):

enter image description here

My code:

g = sns.lmplot('credibility', 'percentWatched', data=data, hue = 'millennial', markers = ["+", "."], x_jitter = True, y_jitter = True, size=5) g.set(xlabel = 'Credibility Ranking\n ← Low       High  →', ylabel = 'Percent of Video Watched [%]') 

You may notice the plot's legend title is simply the variable name ('millennial') and the legend items are the variable's values (0, 1). How can I edit the legend's title and labels? Ideally, the legend's title would be 'Generation' and the labels would be "Millennial" and "Older Generations"

like image 408
Oliver G Avatar asked Jul 19 '17 21:07

Oliver G


People also ask

How do I edit my legend in Seaborn?

To change the position of a legend in a seaborn plot, you can use the plt. legend() command. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.

How do I change my label on Seaborn?

Use the set_xlabel() and set_ylabel() Functions to Set the Axis Labels in a Seaborn Plot. A seaborn plot returns a matplotlib axes instance type object. We can use the set_xlabel() and set_ylabel to set the x and y-axis label respectively. We can use the fontsize parameter to control the size of the font.

How do you add a legend title in Seaborn?

By default, seaborn automatically adds a legend to the graph. Notice the legend is at the top right corner. If we want to explicitly add a legend, we can use the legend() function from the matplotlib library.


1 Answers

Took me a while to read through the above. This was the answer for me:

import seaborn as sns import matplotlib.pyplot as plt tips = sns.load_dataset("tips")  g = sns.lmplot(     x="total_bill",      y="tip",      hue="smoker",      data=tips,       legend=False )  plt.legend(title='Smoker', loc='upper left', labels=['Hell Yeh', 'Nah Bruh']) plt.show(g) 

Reference this for more arguments: matplotlib.pyplot.legend

enter image description here

like image 143
Glen Thompson Avatar answered Oct 06 '22 02:10

Glen Thompson