首页 > 解决方案 > python subplot plot.bar from one dataframe and legend from a different dataframe

问题描述

I have two data sets below

Df1:

    Cluster     HPE     FRE     UNE
0        0  176617  255282   55881
1        1  126130    7752  252045
2        2   12613   52326    7434

I draw a bar diagram. (This is not an exact code of mine, but it will give you an idea)

Hd=list(Df1.columns)
for i in range(1,4):
  subp=Fig.add_subplot(3,1,i) 
  plt.bar(Df1[Hd[0]],DataFrame[Hd[i]],width=0.4)

df1.bar plot

Now I want a legend based on a second data set of centroids.

Df2:

   Cluster          HPE         FRE          UNE
0        0    19.282091  106.470162  1620.005037
1        1  1790.500000  367.625000   537.856177
2        2  1500.000000  180.148148  4729.275913

HPE subplot should have HPE column values (19.282091,1790.500000,1500.000000) as below.

The requirement

How can I do that?

标签: pythonpandasdataframematplotliblegend

解决方案


将图例显式设置为从第二个数据帧获得的字符串(如果您想要条形的颜色框):

subp.legend([str(a) + ' - ' + str(b) for a, b in zip(df2['Cluster'].tolist(), df2['HPE'].tolist())])

或者只是使用一张桌子:

plt.table(cellText=df2[['Cluster', 'HPE']].values, loc='upper right') 

推荐阅读