matplotlib 向二元kdeot添加标签

h5qlskok  于 2022-11-15  发布在  其他
关注(0)|答案(1)|浏览(192)

我喜欢multiple bivariate KDE plots的Seborn示例,但我希望使用标准的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()

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

5ssjco0h

5ssjco0h1#

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

相关问题