熊猫通过groupby元素设置标签图例

时间:2019-09-11 09:47:18

标签: pandas matplotlib

我正在同一轴上绘制2个数据帧的kde分布,并且我需要设置一个图例,说明哪条线是哪个数据帧。现在,这是我的代码:

fig, ax = plt.subplots(figsize=(15,10))

for label, df in dataframe1.groupby('ID'):
     dataframe1.Value.plot(kind="kde", ax=ax,color='r')
for label, df in dataframe2.groupby('ID'):
    dataframe2.Value.plot(kind='kde', ax=ax, color='b')
plt.legend()
plt.title('title here', fontsize=20)
plt.axvline(x=np.pi,color='gray',linestyle='--')
plt.xlabel('mmHg', fontsize=16)
plt.show()

但是结果是这样的:enter image description here

如何将图例中的图例显示为“来自df1的值”和“来自df2的结果”?

编辑: 使用以下代码,我正确地获得了问题的结果。但是在某些数据框中,我得到以下结果:

fig, ax = plt.subplots(figsize=(15,10))
sns.kdeplot(akiPEEP['Value'], color="r", label='type 1', ax=ax)
sns.kdeplot(noAkiPEEP['Value'], color="b",label='type 2', ax=ax)
plt.legend()
plt.title('d', fontsize=20)
plt.axvline(x=np.pi,color='gray',linestyle='--')
plt.xlabel('value', fontsize=16)
plt.show()

enter image description here

我正在绘制的分布:

该如何解决?另外,在该分布上绘制滚动平均值还是会变得太重呢?

1 个答案:

答案 0 :(得分:0)

我不确定我是否理解您的问题,但是从您的代码来看,您似乎正在尝试在数据框中为每个ID值绘制一个KDE。在这种情况下,您将必须这样做:

for label, df in dataframe1.groupby('ID'):
     df.Value.plot(kind="kde", ax=ax,color='r', label=label)

请注意,我在for循环的正文中将dataframe1替换为dfdf对应于子数据帧,其中列ID中的所有元素的值为label