Drawing Grouped ggplot2 Barchart in R (Example Code)
In this article you’ll learn how to create a barchart with groups in R programming.
Preparing the Example
data(iris) # Creating example data sset iris$group <- letters[1:2] iris <- iris[ , c(1, 5, 6)] head(iris) # Head of example data set # Sepal.Length Species group # 1 5.1 setosa a # 2 4.9 setosa b # 3 4.7 setosa a # 4 4.6 setosa b # 5 5.0 setosa a # 6 5.4 setosa b |
data(iris) # Creating example data sset iris$group <- letters[1:2] iris <- iris[ , c(1, 5, 6)] head(iris) # Head of example data set # Sepal.Length Species group # 1 5.1 setosa a # 2 4.9 setosa b # 3 4.7 setosa a # 4 4.6 setosa b # 5 5.0 setosa a # 6 5.4 setosa b
Example: Create Grouped ggplot2 Barplot of Iris Flower Data
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2 |
install.packages("ggplot2") # Install ggplot2 package library("ggplot2") # Load ggplot2
ggplot(iris, # Drawing grouped barplot aes(x = Species, y = Sepal.Length, fill = group)) + geom_bar(stat = "identity", position = "dodge") |
ggplot(iris, # Drawing grouped barplot aes(x = Species, y = Sepal.Length, fill = group)) + geom_bar(stat = "identity", position = "dodge")