小编给大家分享一下如何使用ggplot2绘制堆叠柱状图,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!
绘制堆叠柱状图,重点重点在于geom_bar中postion="stack",
dat type Sample Num 1 A sample1 90 2 B sample1 34 3 C sample1 56 4 D sample1 99 5 E sample1 15 6 A sample2 50 7 B sample2 20 8 C sample2 24 9 D sample2 70 10 E sample2 14
绘图部分将geom_bar(position="stack")设置成堆叠类型可以生成堆叠的柱状图,默认fill的顺序是”Sample“因子的顺序,如果不是有序因子一般是字母排序的顺序。
p = ggplot(dat, aes(x = type,y = Num,fill = Sample))+ geom_bar(stat ="identity",width = 0.6,position ="stack")+ scale_fill_manual(values = c("red","blue"))+ labs(x = "",y = "", title = "test")+ geom_text(aes(label = dat$Num),position=position_stack(vjust =0.5),size = 5)+ guides(fill = guide_legend(reverse = F))+ theme(plot.title = element_text(size = 25,face = "bold", vjust = 0.5, hjust = 0.5), legend.title = element_blank(), legend.text = element_text(size = 18, face = "bold"), legend.position = 'right', legend.key.size=unit(0.8,'cm')) print(p)
反向堆叠操作position_stack(reverse=T)
p = ggplot(dat, aes(x = type,y = Num,fill = Sample))+ geom_bar(stat ="identity",width = 0.6,position =position_stack(reverse = T))+ scale_fill_manual(values = c("red","blue"))+ labs(x = "",y = "", title = "test")+ geom_text(aes(label = dat$Num),position=position_stack(reverse =T,vjust =0.5),size = 5)+ guides(fill = guide_legend(reverse = F))+ theme(plot.title = element_text(size = 25,face = "bold", vjust = 0.5, hjust = 0.5), legend.title = element_blank(), legend.text = element_text(size = 18, face = "bold"), legend.position = 'right', legend.key.size=unit(0.8,'cm')) print(p)
以上是“如何使用ggplot2绘制堆叠柱状图”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。