How to use ggplot2 to draw stacked histogram
Xiaobian to share with you how to use ggplot2 to draw stacked histograms, I believe most people still do not know how, so share this article for everyone's reference, I hope you have a lot of harvest after reading this article, let's go to understand it together!
Draw a stacked histogram, focusing on poster ="stack" in geom_bar,
dat type Sample Num1 A sample1 902 B sample1 343 C sample1 564 D sample1 995 E sample1 156 A sample2 507 B sample2 208 C sample2 249 D sample2 7010 E sample2 14
The plot section sets geom_bar(position="stack") to stack type to generate stacked histograms. The default fill order is the order of "Sample" factors. If it is not ordered, it is generally the order of alphabetical sorting.
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) The above is "How to draw stacked histograms using ggplot2" All the contents of this article, thank you for reading! I believe that everyone has a certain understanding, hope to share the content to help everyone, if you still want to learn more knowledge, welcome to pay attention to the industry information channel!