正确地将图例添加到海洋联合图

时间:2020-07-16 15:02:34

标签: python matplotlib seaborn

我在海洋联合图中绘制了两个分布,像这样:

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

关于图例的通知,setosavirginica的左侧没有颜色。有什么方法可以将图例正确添加到seaborn的关节图中?

1 个答案:

答案 0 :(得分:2)

您可以将label添加到两个绘图调用中,并从ax.legend()中删除名称。因此,完整的示例(请参见#CHANGE HERE注释):

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