简体   繁体   English

Pandas plot 在同一个条形图上具有不同变量的几个 df

[英]Pandas plot several df with different variables on the same barplot

I have 4 Dataframes with different location: Indonesia, Singapore, Malaysia and Total each of them containing the percentage of the 5 top revenue-generating products.我有 4 个不同位置的数据框:印度尼西亚、新加坡、马来西亚和 Total,每个数据框都包含 5 个最高创收产品的百分比。 I have plotted them separately.我已经分别绘制了它们。

I want to combine them together on one plot where X-axis shows different locations and top-revenue-generating products for each location.我想将它们组合在一个 plot 上,其中 X 轴显示不同的位置以及每个位置的最高收入产生产品。

I have printed data frames and as you can see they have different products in them.我已经打印了数据框,您可以看到它们中有不同的产品。

print(Ind_top_cat, Sin_top_cat, Mal_top_cat, Tot_top_cat)打印(Ind_top_cat、Sin_top_cat、Mal_top_cat、Tot_top_cat)

Category     Amt   
M020P     0.144131
MH        0.099439
ML        0.055052
PB        0.050057
PPDR      0.048315                

Category     Amt   
ML        0.480781
M015      0.073034
PPDR      0.035412
M025      0.033418
M020      0.031836                

Category     Amt   
TN        0.343650
PPDR      0.190773
NMCN      0.118425
M015      0.047539
NN        0.038140                

Category     Amt      
M020P     0.158575
MH        0.092012
ML        0.064179
PPDR      0.050803
PB        0.044301

Thanks to joelostblom I was able to construct a plot, however, there are still some issues.感谢 joelostblom,我能够构建一个 plot,但是,仍然存在一些问题。 enter image description here在此处输入图像描述

all_countries = pd.concat([Ind_top_cat, Sin_top_cat, Mal_top_cat, Tot_top_cat])
all_countries['Category'] = all_countries.index
sns.barplot(x='Country', y='Amt',hue = 'Category',data=all_countries)

Is there any way I can put legend values on the x-axis (no need to colour categories on I want to instead colour countries), and put data values on top of bars.有什么办法可以将图例值放在 x 轴上(不需要在我想为国家着色的类别上着色),并将数据值放在条形顶部。 Also, bars are not centred and have no idea how to solve it.此外,条不居中,不知道如何解决它。

You could create a new column in each dataframe with the country name, eg您可以使用国家名称在每个 dataframe 中创建一个新列,例如

Ind_top_cat['Country'] = 'Indonesia'
Sin_top_cat['Country'] = 'Singapore'

The you can create one big dataframe by concatenating the country dataframes together:您可以通过将国家/地区数据框连接在一起来创建一个大的 dataframe:

all_countries = pd.concat([Ind_top_cat, Sin_top_cat])

And finally, you can use a high level plotting library such as seaborn to assign one column to the x-axis location and one to the color of the bars:最后,您可以使用 seaborn 等高级绘图库将一列分配给 x 轴位置,并将一列分配给条形的颜色:

import seaborn as sns

sns.barplot(x='Country', y='Amt', color='Category', data=all_countries)

You can scroll down to the second example on this page to get an idea what such a plot would look like (also pasted below):您可以向下滚动到此页面上的第二个示例,以了解此类 plot 的外观(也粘贴在下面):

添加情节图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM