简体   繁体   English

使用循环绘制多元分组条形图

[英]plotting multivariate grouped bar graph using loop

I am trying to create a grouped bar chart with multiple subplots using matplotlib and pandas.我正在尝试使用 matplotlib 和 pandas 创建具有多个子图的分组条形图。 I am able to create it manually defining the plots according to the values of the datatframe, but I want to get it automated with loops.我可以根据数据帧的值手动定义图来创建它,但我想通过循环使其自动化。 I have tried many ways doing a loop, but running into one or other error every time.我尝试了很多方法来循环,但每次都会遇到一个或其他错误。 Being a beginner in both programming and python, I am getting lost.作为编程和 python 的初学者,我迷路了。 here's my data: sales3这是我的数据: sales3

The code I have written to get the expected output:我为获得预期的 output 而编写的代码:

sales3 = sales.groupby(["Region","Tier"])[["Sales2015","Sales2016"]].sum().round().astype("int64")
sales3.reset_index(inplace=True)
fig,(ax1,ax2,ax3) = plt.subplots(nrows=1,ncols=3,sharex=True,sharey=True,figsize=(10,6))
sales3[sales3["Region"]=="Central"].plot(kind="bar",x="Tier",y=["Sales2015","Sales2016"],ax=ax1)
ax1.set_title("Central")
sales3[sales3["Region"]=="East"].plot(kind="bar",x="Tier",y=["Sales2015","Sales2016"],ax=ax2)
ax2.set_title("East")
sales3[sales3["Region"]=="West"].plot(kind="bar",x="Tier",y=["Sales2015","Sales2016"],ax=ax3)
ax3.set_title("West")
plt.tight_layout()

output: expected output output:预期 output

Please guide how do I write it using a loop or any automated way.请指导我如何使用循环或任何自动方式编写它。 Say, I have another region like "North" /"South" added in future or a new Tier introduced, what will be the best way to program that would accommodate such new additions.比如说,我将来会添加另一个区域,例如“北方”/“南方”,或者引入了一个新的等级,什么是最好的编程方式来适应这些新增内容。

You can iterate through the axes and regions:您可以遍历轴和区域:

sales3 = sales.groupby(["Region","Tier"])[["Sales2015","Sales2016"]].sum().round().astype("int64")
sales3.reset_index(inplace=True)
fig,axes = plt.subplots(nrows=1,ncols=3,sharex=True,sharey=True,figsize=(10,6))

# define regions to plot
regions = ["Central", "East", "West"]

# iterate over regions and axes using zip()
for region, ax in zip(regions,axes):
    sales3[sales3["Region"]==region].plot(kind="bar",x="Tier",y=["Sales2015","Sales2016"],ax=ax)
    ax.set_title(region)
plt.tight_layout()

I think the key is using pythons built-in zip function which is documented here .我认为关键是使用 pythons 内置 zip function 记录在这里

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

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