添加标签到Seaborn双变量KDE图

时间:2018-04-24 00:16:06

标签: python matplotlib seaborn

我喜欢multiple bivariate KDE plots的Seaborn示例,但我希望在该示例中使用标准的matplotlib图例而不是自定义标签。

以下是我尝试使用图例的示例:

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()

Plot with no legend

kdeplot()的标签参数似乎适用于单变量KDE图,但不适用于双变量图。如何添加图例?

1 个答案:

答案 0 :(得分:1)

根据this tutorial,我了解到您可以将标签传递给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()

Plot with legend