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

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)

r graph figure 1 creating horizontal barplot base r ggplot2

Example 2: Creating Barplot with Horizontal Bars Using coord_flip() Function of ggplot2 Package

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()

r graph figure 2 creating horizontal barplot base r ggplot2

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top