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 |
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 |
barplot(iris_sum$values) # Default y-axis
barplot(iris_sum$values, ylim = c(0, 700)) # User-defined y-axis |
barplot(iris_sum$values, ylim = c(0, 700)) # User-defined y-axis
Example 2: Modify Y-Axis of ggplot2 Barplot
install.packages("ggplot2") # Install & load ggplot2 library("ggplot2") |
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 |
ggp <- ggplot(iris_sum, # Default y-axis aes(x = group, y = values)) + geom_bar(stat = "identity") ggp # Print ggplot2 plot to RStudio console
ggp + ylim(0, 700) # User-defined y-axis |
ggp + ylim(0, 700) # User-defined y-axis