How to use ggplot2 to draw grouped histograms and separate them within groups
This article mainly shows you "how to use ggplot2 to draw group histogram and group separation", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use ggplot2 to draw group bar chart and group separation" this article.
The grouping histogram was drawn by ggplot2 and separated within the group.
Load R package, set data
Library ('ggplot2') library (' reshape2') A = c ("A", "B", "C", "D", "E") B = c (9014) dat = data.frame (A type, "sample1", "sample2") dat = melt (dat,variable.name= "Sample", value.name = "Num") head (dat)
Draw a grouped bar chart
P = ggplot (dat, aes (x = type,y = Num,fill = Sample)) + # position = "dodge" Geom_bar (stat = "identity", width = 0.6) position = "dodge") + scale_fill_manual (values = c ("red", "blue")) + # sets the color labs (x = "", y = "") Title = "test") + # coordinate label and picture title geom_text (aes (label = dat$Num), position=position_dodge (width = 0.5), size = 5mage vjust =-0.25) + # sets the label text on the column The position_dodge (width=0.5) setting of the text ensures the separation width. Guides (fill = guide_legend (reverse = F)) + # legend order reverses theme (plot.title = element_text (size = 25 bold = "bold", vjust = 0.5, hjust = 0.5), # picture title text size position legend.title = element_blank () # Legend name is empty legend.text = element_text (size= 18, face = "bold"), # Legend text size legend.position = 'right', # Legend location legend.key.size=unit (0.8) 'cm')) # Legend size print (p)
Set interval within group
The position_dodge (width=0.8) of p = ggplot (dat, aes (x = type,y = Num,fill = Sample)) + # is greater than the wide width= 0.6 point, which can make the gap between the columns in the group rather than fit. The position setting of geom_bar (stat = "identity", width= 0.6 position = position_dodge (width=0.8)) + scale_fill_manual (values = c ("red", "blue")) + labs (x = "", y = ", title =" test ") + # text is similar to bar's position geom_text (label = dat$Num), position=position_dodge (width= 0.9), size = 5 Vjust =-0.25) + guides (fill = guide_legend (reverse = F)) + theme (plot.title = element_text (size= 25pedface = "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) above are all the contents of the article "how to draw grouped histograms and separate them within groups using ggplot2" Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!