Creating Horizontal Barplot in Base R & ggplot2 (2 Examples)
This tutorial shows how to create a barchart with horizontally aligned bars in the R programming language.
Setting up the Examples
data(iris) # Loading iris data iris_new <- iris[c(1, 51, 101), # Subset of iris c("Petal.Length", "Species")] iris_new # Print final example data set # Petal.Length Species # 1 1.4 setosa # 51 4.7 versicolor # 101 6.0 virginica |
data(iris) # Loading iris data iris_new <- iris[c(1, 51, 101), # Subset of iris c("Petal.Length", "Species")] iris_new # Print final example data set # Petal.Length Species # 1 1.4 setosa # 51 4.7 versicolor # 101 6.0 virginica
Example 1: Creating Barplot with Horizontal Bars Using barplot() Function & horiz Argument in Base R
barplot(iris_new$Petal.Length ~ iris_new$Species, # Create Base R barchart with horizontal bars horiz = TRUE) |
barplot(iris_new$Petal.Length ~ iris_new$Species, # Create Base R barchart with horizontal bars horiz = TRUE)
Example 2: Creating Barplot with Horizontal Bars Using coord_flip() Function of ggplot2 Package
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2") |
install.packages("ggplot2") # Install & load ggplot2 package library("ggplot2")
ggplot(iris_new, aes(Species, Petal.Length)) + # Create ggplot2 barchart with horizontal bars geom_bar(stat = "identity") + coord_flip() |
ggplot(iris_new, aes(Species, Petal.Length)) + # Create ggplot2 barchart with horizontal bars geom_bar(stat = "identity") + coord_flip()