2

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

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • @mnist This is very helpful and I think the solution. Thank you very much. Though I would like to know if there is a possibility to set this limits without setting breaks that are divisible by 39. So to say with individual gaps between 0 and 39. So for example like 0-10-20-30-39. – TarJae Mar 20 '22 at 13:46
  • 1
    seq just creates a vector. you can define whatever you want using `c(...)` – mnist Mar 20 '22 at 13:48
  • `scale_y_continuous(limits = c(0, 39), breaks = seq(c(0, 10, 20, 39)))` does not work. – TarJae Mar 20 '22 at 13:55
  • Ah ok now I see it. @mnist please provide as answer!. Thank you all! – TarJae Mar 20 '22 at 13:56

2 Answers2

2

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)

Peter
  • 11,500
  • 5
  • 21
  • 31
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

Quinten
  • 35,235
  • 5
  • 20
  • 53