如何在相关 KDE 图上添加标签?

问题描述 投票:0回答:1

我正在尝试使用seaborn.kdeplot 绘制两个数据集的KDE。我想为每个数据集添加单独的标签,但我无法让标签正常工作。这是我的代码:

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

np.random.seed(0)
data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(2, 1, 500)

# Plot the KDEs with weights
plt.figure(figsize=(6, 6))

sns.kdeplot([data1, data2], label=['Data 1', 'Data 2'], fill=True, bw_adjust=1)

plt.title('Relative density plots')
plt.xlabel('Value')
plt.ylabel('Density')
plt.legend()
plt.show()

enter image description here

但是,这并没有给我正确的标签。两个数据集均已绘制,但标签未正确分配。

给定多个数组的列表,我想添加相应标签的列表,但这似乎不起作用。关于如何实现这一目标有什么想法吗?

plot label kernel-density
1个回答
0
投票

下面的代码似乎可以做到这一点,使用

matplotlib.patches

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

np.random.seed(0)
data1 = np.random.normal(0, 1, 1000)
data2 = np.random.normal(2, 1, 500)

# Plot the KDEs with weights
plt.figure(figsize=(6, 6))

sns.kdeplot([data1, data2], fill=True, bw_adjust=1)

labels = ['Data 1', 'Data 2']
handles = [mpatches.Patch(facecolor=color, label=label, alpha=0.5) for color, label in zip(plt.rcParams['axes.prop_cycle'].by_key()['color'], labels)]

plt.title('Relative density plots')
plt.xlabel('Value')
plt.ylabel('Density')
plt.legend(handles=handles)
plt.show()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.