Reputation: 880
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)
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?
Upvotes: 2
Views: 6775
Reputation: 8790
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)
Upvotes: 3