优势,有数据就行了自己会画图。
用法,先提取数据,整合成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 结果: