首页 > 解决方案 > 如何在 Pandas 或 matplotlib 中绘制条形图

问题描述

嗨,我希望有人可以帮助我

我已经完成了下面的编码

import pandas as pd
import matplotlib.pyplot as plt

%matplotlib inline
#set index on the quarter
df_csv= pd.read_csv('retrenchment-by-industry-level-1.csv', index_col='year')

#load into data frame for both column industry1 and retrench
df= pd.DataFrame(df_csv, columns=['industry1','retrench'])


#load into mau_df with industry1 that is equal to manufacturing
mau_df= df.loc[df['industry1']=='manufacturing']
mau_df=mau_df['retrench'].astype(int)
#load into const_df with industry1 that is equal to construction
const_df= df.loc[df['industry1']=='construction']
const_df= const_df['retrench'].astype(int)

#load into serv_df with industry1 that is equal to services
serv_df= df.loc[df['industry1']=='services']
serv_df= serv_df['retrench'].astype(int)

#load into oth_df with industry1 that is equal to other
oth_df= df.loc[df['industry1']=='others']
oth_df= oth_df.replace(r'-',0)
oth_df=oth_df['retrench'].astype(int)
print(mau_df)
print (oth_df)

数据集如下

year
1998    20700
1999     8370
2000     7500
2001    15680
2002     9660
2003     7480
2004     4700
2005     7080
2006     8860
2007     5500
2008    10430
2009    13640
2010     4490
2011     4460
2012     4050
2013     5000
2014     3970
2015     5210
2016     6280
2017     3790
2018     2570
2019     2790
Name: retrench, dtype: int32



year
1998     30
1999     10
2000      0
2001    200
2002    180
2003    270
2004    310
2005     20
2006     70
2007     20
2008     50
2009     90
2010      0
2011     50
2012     10
2013     10
2014     10
2015     80
2016    100
2017     20
2018      0
2019     30
Name: retrench, dtype: int32

如何在条形图上绘制两个条形图?先感谢您

标签: pandasmatplotlib

解决方案


  • 绘制多个条的最简单方法是让它们成为同一数据框中的列
  • 合并两个数据框,因此它们是列
  • 然后简单地调用plot()
import matplotlib.pyplot as plt
import pandas as pd

mau_df = pd.DataFrame({"year": [1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019], 
                       "val": [20700, 8370, 7500, 15680, 9660, 7480, 4700, 7080, 8860, 5500, 10430, 13640, 4490, 4460, 4050, 5000, 3970, 5210, 6280, 3790, 2570, 2790]}
                     ).set_index("year")
oth_df = pd.DataFrame({"year": [1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019], 
                       "val": [30, 10, 0, 200, 180, 270, 310, 20, 70, 20, 50, 90, 0, 50, 10, 10, 10, 80, 100, 20, 0, 30]}
                     ).set_index("year")
aaa_df = oth_df * .75


fig, ax = plt.subplots(2, figsize=[10,6])

# values are different scales,  just multiply for them to show
(mau_df
 .merge(oth_df*100, on="year")
 .merge(aaa_df*100, on="year")
 .set_axis(["mau","oth","aaa"], axis=1)
 .plot(ax=ax[0], kind="bar")
)

pd.concat([mau_df, oth_df*100, aaa_df*100], axis=1).set_axis(["mau","oth","aaa"], axis=1).plot(ax=ax[1], kind="bar")

在此处输入图像描述


推荐阅读