简体   繁体   English

为Seaborn二元KDE图添加标签

[英]Add labels to Seaborn bivariate KDE plot

I like the Seaborn example of multiple bivariate KDE plots , but I was hoping to use a standard matplotlib legend instead of the custom labels in that example. 我喜欢多个双变量KDE图的Seaborn示例,但我希望使用标准的matplotlib图例代替该示例中的自定义标签。

Here's an example where I tried to use a legend: 这是我尝试使用图例的示例:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

cmaps = ['Reds', 'Blues', 'Greens', 'Greys']

np.random.seed(0)
for i, cmap in enumerate(cmaps):
    offset = 3 * i
    x = np.random.normal(offset, size=100)
    y = np.random.normal(offset, size=100)
    label = 'Offset {}'.format(offset)
    sns.kdeplot(x, y, cmap=cmaps[i]+'_d', label=label)
plt.title('Normal distributions with offsets')
plt.legend(loc='upper left')
plt.show()

没有图例的情节

The label parameter to kdeplot() seems to work for univariate KDE plots, but not for bivariate ones. kdeplot()的label参数似乎适用于单变量KDE图,但不适用于双变量KDE图。 How can I add a legend? 如何添加图例?

Based on this tutorial , I learned that you can pass the labels in to the legend() function. 根据本教程 ,我了解到可以将标签传递给legend()函数。

import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np

cmaps = ['Reds', 'Blues', 'Greens', 'Greys']

np.random.seed(0)
label_patches = []
for i, cmap in enumerate(cmaps):
    offset = 3 * i
    x = np.random.normal(offset, size=100)
    y = np.random.normal(offset, size=100)
    label = 'Offset {}'.format(offset)
    sns.kdeplot(x, y, cmap=cmaps[i]+'_d')
    label_patch = mpatches.Patch(
        color=sns.color_palette(cmaps[i])[2],
        label=label)
    label_patches.append(label_patch)
plt.title('Normal distributions with offsets')
plt.legend(handles=label_patches, loc='upper left')
plt.show()

图例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM