Force individual y axis limits

Viewed 59

I have this dataframe:

df <- structure(list(x = c(2L, 3L, 4L, 5L, 1L), y = c(24L, 27L, 18L, 
23L, 28L)), class = "data.frame", row.names = c("1", "2", "3", 
"4", "5"))

  x  y
1 2 24
2 3 27
3 4 18
4 5 23
5 1 28

I want to set the y axis limits to 0 and 39 but I get 0 and 40.

Here is my code:

library(ggplot2)

ggplot(df, aes(x, y))+
  geom_point()+
  ylim(0,39)

enter image description here

2 Answers

You can set breaks as you wish using the breaks argument. Breaks do not need to be a regular sequence.

  df <- structure(list(x = c(2L, 3L, 4L, 5L, 1L), y = c(24L, 27L, 18L, 
                                                        23L, 28L)), class = "data.frame", row.names = c("1", "2", "3", 
                                                                                                        "4", "5"))
  
  
  library(ggplot2)
  
  ggplot(df, aes(x, y))+
    geom_point()+
    scale_y_continuous(limits = c(0, 39),
                       breaks = c(0, 10, 20, 30, 39))

Created on 2022-03-20 by the reprex package (v2.0.1)

You can change the limits and breaks in the scale_y_continuous function to whatever you want. To visualize you can use this code:

df <- structure(list(x = c(2L, 3L, 4L, 5L, 1L), y = c(24L, 27L, 18L, 
                                                      23L, 28L)), class = "data.frame", row.names = c("1", "2", "3", 
                                                                                                      "4", "5"))

    library(ggplot2)
    
    ggplot(df, aes(x, y))+
      geom_point()+
      scale_y_continuous(limits = c(0, 39), breaks = seq(0, 39, by = 13))

Output:

enter image description here

Related