2

I have two distributions plotting in a seaborn jointplot like so:

graph = sns.jointplot(setosa.sepal_width, setosa.sepal_length,
                 cmap="Reds", kind="kde", marginal_kws={"color":"r", "alpha":.2}, shade=True, shade_lowest=False, alpha=.5)

graph.x = virginica.sepal_width
graph.y = virginica.sepal_length
graph.plot_joint(sns.kdeplot, cmap="Blues", shade=True, shade_lowest=False, alpha=.5)
ax = plt.gca()
ax.legend(["setosa", "virginica"])
graph.plot_marginals(sns.kdeplot, color='b', shade=True, alpha=.2, legend=False)

Output Image

Notice on the legend, that the setosa and virginica have no color to their left. Is there any way to correctly add a legend to a jointplot in seaborn?

gnodab
  • 850
  • 6
  • 15

1 Answers1

3

You can add label to both of your plotting calls, and remove the names from ax.legend(). So the full example (see the #CHANGE HERE comments):

import seaborn as sns
import matplotlib.pyplot as plt

#I'm taking a stab at defining what you had
#the resulting plot is different
#but method still applies
iris = sns.load_dataset("iris")
setosa = iris[iris['species'] == 'setosa']
virginica = iris[iris['species'] == 'virginica']

graph = sns.jointplot(setosa.sepal_width, setosa.sepal_length,
                 cmap="Reds", kind="kde", marginal_kws={"color":"r", "alpha":.2}, shade=True, shade_lowest=False, alpha=.5,
                 label='setosa')      ## CHANGE HERE

graph.x = virginica.sepal_width
graph.y = virginica.sepal_length
graph.plot_joint(sns.kdeplot, cmap="Blues", shade=True, shade_lowest=False, alpha=.5, label='virginica')   ## CHANGE HERE
graph.set_axis_labels()
ax = plt.gca()
ax.legend()  #CHANGE HERE
graph.plot_marginals(sns.kdeplot, color='b', shade=True, alpha=.2, legend=False)

enter image description here

Tom
  • 8,310
  • 2
  • 16
  • 36
  • 1
    Thank you. Plot is different because I accidentally labelled `virginica` as `setosa`. This is exactly what I was looking for though! – gnodab Jul 16 '20 at 16:59