Change Y-Axis Range of Barchart in R (2 Examples)

In this R tutorial you’ll learn how to adjust the range of barchart ylim values.

Preparing the Examples

data(iris)                                            # Loading iris data set
iris_sum <- data.frame(group = levels(iris$Species),  # Modify iris data
                       values = c(sum(iris$Sepal.Length[iris$Species == "setosa"]),
                                  sum(iris$Sepal.Length[iris$Species == "versicolor"]),
                                  sum(iris$Sepal.Length[iris$Species == "virginica"])))
iris_sum                                              # Print example data
#        group values
# 1     setosa  250.3
# 2 versicolor  296.8
# 3  virginica  329.4

Example 1: Modify Y-Axis of Base R Barplot

barplot(iris_sum$values)                              # Default y-axis

r graph figure 1 change y axis range barchart

barplot(iris_sum$values, ylim = c(0, 700))            # User-defined y-axis

r graph figure 2 change y axis range barchart

Example 2: Modify Y-Axis of ggplot2 Barplot

install.packages("ggplot2")                           # Install & load ggplot2
library("ggplot2")
ggp <- ggplot(iris_sum,                               # Default y-axis
              aes(x = group, y = values)) +
  geom_bar(stat = "identity")
ggp                                                   # Print ggplot2 plot to RStudio console

r graph figure 3 change y axis range barchart

ggp + ylim(0, 700)                                    # User-defined y-axis

r graph figure 4 change y axis range barchart

Leave a Reply

Your email address will not be published.

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