在 Pandas 图中添加图例 [英] Adding Legends in Pandas Plot

查看:164
本文介绍了在 Pandas 图中添加图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Pandas Plot 绘制密度图.但是我无法为每个图形添加适当的图例.我的代码和结果如下:-

I am plotting Density Graphs using Pandas Plot. But I am not able to add appropriate legends for each of the graphs. My code and result is as as below:-

for i in tickers:
    df = pd.DataFrame(dic_2[i])
    mean=np.average(dic_2[i])
    std=np.std(dic_2[i])
    maximum=np.max(dic_2[i])
    minimum=np.min(dic_2[i])
    df1=pd.DataFrame(np.random.normal(loc=mean,scale=std,size=len(dic_2[i])))
    ax=df.plot(kind='density', title='Returns Density Plot for '+ str(i),colormap='Reds_r')
    df1.plot(ax=ax,kind='density',colormap='Blues_r')

您可以在图片右上角的框中看到,图例变为 0.如何在那里添加有意义的内容?

You can see in the pic, top right side box, the legends are coming as 0. How do I add something meaningful over there?

print(df.head())
           0
0  -0.019043
1 -0.0212065
2  0.0060413
3  0.0229895
4 -0.0189266

推荐答案

我认为您可能想要重新构建您创建图表的方式.一个简单的方法是在绘图之前创建 ax:

I think you may want to restructure the way you've created the graph. An easy way to do this is to create the ax before plotting:

# sample data
df = pd.DataFrame()
df['returns_a'] = [x for x in np.random.randn(100)]
df['returns_b'] = [x for x in np.random.randn(100)]
print(df.head())
   returns_a  returns_b
0   1.110042  -0.111122
1  -0.045298  -0.140299
2  -0.394844   1.011648
3   0.296254  -0.027588
4   0.603935   1.382290

fig, ax = plt.subplots()

然后我使用变量中指定的参数创建了数据框:

I then created the dataframe using the parameters specified in your variables:

mean=np.average(df.returns_a)
std=np.std(df.returns_a)
maximum=np.max(df.returns_a)
minimum=np.min(df.returns_a)

pd.DataFrame(np.random.normal(loc=mean,scale=std,size=len(df.returns_a))).rename(columns={0: 'std_normal'}).plot(kind='density',colormap='Blues_r', ax=ax)
df.plot('returns_a', kind='density', ax=ax)

您正在使用的第二个数据框默认使用 0 列创建.您需要重命名它.

This second dataframe you're working with is created by default with column 0. You'll need to rename this.

这篇关于在 Pandas 图中添加图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆