ggplot2画分组的堆积柱形图简单小例子_折线图 image.png


之前有读者在公众号留言问开头的图应该如何画?我第一眼看到这个图简单的理解为了堆积柱形图,加折线图。所以基本的想法就是构造两份数据来画这个图,第一份用来画堆积柱形图,第二份用来画折线图。但是准备画图的时候才意识到这个堆积柱形图是一个分组的堆积柱形图,我之前画的都是单独的,没有画过分组的。一时还想不起来该如何画这个分组的堆积柱形图了。



今天找资料的时候找到一个链接 ​​Beginners Guide to Creating Grouped and Stacked Bar Charts in R With ggplot2 | theduke.at​​ 这里介绍了分组的堆积柱形图可以用分面的方式来实现,比如如下代码


dat <- data.frame(
year=factor(sample(2010:2014, 400, replace=T)),
continent=factor(sample(c("EU", "US", "Asia"),
400, replace=T)),
gender=factor(sample(c("male", "female"),
400, replace=T)),
amount=sample(20:5000, 400, replace=T)
)
head(dat)
library(ggplot2)
ggplot(dat,aes(x=year,y=amount,fill=gender))+
geom_bar(stat="identity",position = "stack")+
facet_wrap(~continent)+
theme_bw()

ggplot2画分组的堆积柱形图简单小例子_数据集_02 image.png

但是这样分面的话就不能构造数据添加折线图了。

今天还找到了一份参考资料

​r - How to plot a Stacked and grouped bar chart in ggplot? - Stack Overflow​

这里介绍到的方法是分隔数据集,比如还是用上面构造的dat这个数据集

dat$x<-ifelse(dat$continent=="Asia",1,
ifelse(dat$continent=="EU",2,3))
df1<-filter(dat,year==2010)
df2<-filter(dat,year==2011)
df1
df2
ggplot()+
geom_bar(data=df1,
aes(x=x,y=amount,fill=gender),
stat = "identity",position = "stack",width=0.3)+
geom_bar(data=df2,aes(x=x+0.3+0.1,y=amount,fill=gender),
stat="identity",position = "stack",width=0.3)+
scale_x_continuous(breaks = c(1.2,2.2,3.2),
labels = c("Asia","EU","US"))+
scale_fill_manual(values = c("red","blue","orange","yellow"))+
theme_bw()

ggplot2画分组的堆积柱形图简单小例子_ide_03 image.png

这样暂时把分组的堆积柱形图做出来了,如何继续往上叠加折线图今天就不介绍了。后面有时间在来更新。

但是这幅图遇到的问题就是:将数据划分为两组,如何给每一个组填充不同的颜色呢?比如这幅图的填充颜色的代码是

​scale_fill_manual()​​这个只能填充2种颜色,而不能实现2010年的填充红蓝,2011填充绿黄。

大家知道这种填充该如何实现吗?欢迎大家留言!

欢迎大家关注我的公众号

小明的数据分析笔记本