如何在同一个数据帧上制作两个变量的条形图,我想选择2或直到5d

2024-06-24 11:39:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

wilayah   branch   Income Januari 2018    Income Januari 2019    Income Febuari 2018     Income Febuari 2019     Income Jan-Feb 2018     Income Jan-Feb 2019
   1     sunarto   1000                     1500                     2000                     3000                     3333                     4431                    
   1     pemabuk   500                       700                     3000                     3000                     4333                     5431                    
   1     pemalas   2000                     2200                     4000                     3000                     5333                     6431                   
   1     hasuntato 9000                     1200                     6000                     3000                     2222                     2121                     
   1     sibodoh   1000                     1500                     3434                     3000                     2233                     2121                     
...

我希望创建一个条形图,其中x轴是分支中的每个名称(例如sunarto、pemabuk、pemalas等),y轴是收入

假设我将比较sunarto的2018年1月收入和2019年1月收入,pemabuk的2018年1月收入和2019年1月收入,以此类推(x轴上有1个名称,两个值作为两个值的比较)。然后,我将在条形图中从收入2019年1月-2月中的值从高到低排序

我试过:

import matplotlib.pyplot as plt
import pandas as pd

fig, ax = plt.subplots()
ax = df1[["Sunarto","Income Januari 2018", "Income Januari 2019"]].plot(x='branch', kind='bar', color=["g","b"],rot=45)
plt.show()

Tags: import名称branchaspltaxjanfeb
1条回答
网友
1楼 · 发布于 2024-06-24 11:39:29

考虑一个groupby聚合,然后运行DataFrame.plot。下面将在x轴上以不同的收入列作为图例中的彩色编码键排列所有分支

agg_df = df.groupby('branch').sum()

fig, ax = plt.subplots(figsize=(15,5)) 

agg_df.plot(kind='bar', edgecolor='w', ax=ax, rot=22, width=0.5, fontsize = 15)

# ADD TITLES AND LABELS 
plt.title('Income by Branches, Jan/Feb 2018-2019', weight='bold', size=24) 
plt.xlabel('Branch', weight='bold', size=24) 
plt.ylabel('Income', weight='bold', size=20) 

plt.tight_layout()
plt.show() 
plt.clf() 

如果要在特定列上绘制每个单独的分支,请遍历groupby列表:

dfs = df.groupby('branch')

for i,g in dfs:
   ord_cols = (pd.melt(g.drop(columns="wilayah"), id_vars = "branch")
                            .sort_values("value")["variable"].values
              )

   fig, ax = plt.subplots(figsize=(8,4)) 

   (g.reindex(columns=ord_cols)
     .plot(kind='bar', edgecolor='w', ax=ax, rot=0, width=0.5, fontsize = 15)
   )

   # ADD TITLES AND LABELS 
   plt.title('Income by {} Branch, Jan/Feb 2018-2019'.format(i), 
             weight='bold', size=16) 
   plt.xlabel('Branch', weight='bold', size=16) 
   plt.ylabel('Income', weight='bold', size=14) 

   plt.tight_layout()
   plt.show() 

Groupby Plot Outputs

相关问题 更多 >