Python 在熊猫情节中添加图例
我正在用熊猫图绘制密度图。但我无法为每个图表添加适当的图例。我的代码和结果如下:-Python 在熊猫情节中添加图例,python,pandas,plot,Python,Pandas,Plot,我正在用熊猫图绘制密度图。但我无法为每个图表添加适当的图例。我的代码和结果如下:- 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=mea
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。我如何在那里添加有意义的内容
print(df.head())
0
0 -0.019043
1 -0.0212065
2 0.0060413
3 0.0229895
4 -0.0189266
我认为您可能需要重新构建创建图表的方式。一种简单的方法是在打印前创建
ax
:
# 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()
然后,我使用变量中指定的参数创建了数据帧:
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
创建的。你需要重新命名这个
我想出了一个更简单的方法。只需将列名添加到数据帧
for i in tickers:
df = pd.DataFrame(dic_2[i],columns=['Empirical PDF'])
print(df.head())
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])),columns=['Normal PDF'])
ax=df.plot(kind='density', title='Returns Density Plot for '+ str(i),colormap='Reds_r')
df1.plot(ax=ax,kind='density',colormap='Blues_r')
你能发布样本数据吗?@AndrewL-df只有索引的每日返回数据。我正在用df.head()编辑上面的内容