记录:Pyhton用ggplot2画条形图

优势,有数据就行了自己会画图。

用法,先提取数据,整合成DataFrame,这是为了后续绘制堆叠条形图而准备的。很重要数据不是这个格式就不能跑了。如我们的数据是mydata

然后用,套这个格式

base_plot=(ggplot(mydata,aes('Country','value',fill='variable'))+#ggplot(数据,aes('x','y','填充颜色'))
 
geom_bar(stat="identity", color="black", position='fill',width=0.65,size=0.25)+#stat="identity"直接使用数据的值# position='fill'表示条形将按照'value'的百分比堆叠,
 
scale_fill_brewer(palette="YlOrRd")+#颜色的一种,不管
 
coord_flip()+
  theme(
#x,y轴,标题颜色大小
   
axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=
16,face="plain",color="black"),
       legend_title=element_text(size=
18,face="plain",color="black"),
       legend_text = element_text(size=
16,face="plain",color="black"),
    legend_background  =element_blank(),
    legend_position =
'right',
    aspect_ratio =
1.15,
    figure_size = (
6.5, 6.5),#尺寸
    
dpi = 50#分辨率
 
))
print(base_plot)

例子:

df=pd.read_csv('Stackedbar_Data.csv')
Sum_df=df.iloc[:,1:].apply(lambda x: x.sum(), axis=0).sort_values(ascending=True)
meanRow_df=df.iloc[:,1:].apply(lambda x: x.mean(), axis=1)
Sing_df=df['Country'][meanRow_df.sort_values(ascending=True).index]
mydata=pd.melt(df,id_vars='Country')
#mydata['variable']=mydata['variable'].astype("category",categories= Sum_df.index,ordered=True)
#mydata['Country']=mydata['Country'].astype("category",categories= Sing_df,ordered=True)
#mydata['variable']=mydata['variable'].astype(CategoricalDtype(categories= Sum_df.index,ordered=True))
#mydata['Country']=mydata['Country'].astype(CategoricalDtype(categories= Sing_df,ordered=True))


base_plot=(ggplot(mydata,aes('Country','value',fill='variable'))+#ggplot(数据,aes('x','y','填充颜色'))
  geom_bar(stat="identity", color="black", position='fill',width=0.65,size=0.25)+#stat="identity"直接使用数据的值# position='fill'表示条形将按照'value'的百分比堆叠,
  scale_fill_brewer(palette="YlOrRd")+#颜色的一种,不管
  coord_flip()+
  theme(#x,y轴,标题颜色大小
    axis_title=element_text(size=18,face="plain",color="black"),
       axis_text = element_text(size=16,face="plain",color="black"),
       legend_title=element_text(size=18,face="plain",color="black"),
       legend_text = element_text(size=16,face="plain",color="black"),
    legend_background  =element_blank(),
    legend_position = 'right',
    aspect_ratio =1.15,
    figure_size = (6.5, 6.5),#尺寸
     dpi = 50#分辨率
  ))
print(base_plot)
数据
Country,Pensions,Income,Health ,Other services
France,14,5,9,3
Sweden,8,6,7,8
Italy,15,4,7,1
Germany,11,5,8,3
Spain,9,7,7,2
Britain,6,6,8,4
OECD_average,8,5,6,3
United States,7,3,8,1j

结果:

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值