51

I'm having difficulty setting the breaks in my code, I've tried adding breaks=seq(0, 100, by=20) but just can't seem to get it to work right. Essentially I want the Y axis to go from 0-100 with ticks every 20.

    YearlyCI <- read.table(header=T, text='
  Station Year       CI        se
     M-25 2013 56.57098 1.4481561
     M-45 2013 32.39036 0.6567439
      X-2 2013 37.87488 0.7451653
     M-25 2008     74.5       2.4
     M-45 2008     41.6       1.1
     M-25 2004     82.2       1.9
     M-45 2004     60.6       1.0
     ')


library(ggplot2)
ggplot(YearlyCI, aes(x=Year, y=CI, colour=Station,group=Station)) +
  geom_errorbar(aes(ymin=CI-se, ymax=CI+se), colour="black", width=.2) +
  geom_line(size=.8) +
  geom_point(size=4, shape=18) +
  coord_cartesian(ylim = c(0, 100)) +
  xlab("Year") +
  ylab("Mean Condition Index") +
  labs(fill="") +
  theme_bw() +
    theme(legend.justification=c(1,1), legend.position=c(1,1)) 
M--
  • 25,431
  • 8
  • 61
  • 93
user3490557
  • 744
  • 2
  • 6
  • 9

1 Answers1

101

You need to add

+ scale_y_continuous(breaks = seq(0, 100, by = 20))

EDIT: Per comment below, this only works if axis already in the appropriate range. To enforce the range you can extend above code as follows:

+ scale_y_continuous(limits = c(0, 100), breaks = seq(0, 100, by = 20))
adibender
  • 7,288
  • 3
  • 37
  • 41
  • 10
    This only works if your data is already ranging from 0 to 100. If it is not, and you want to force the graph to display the Y axis from 0 to 100 (with breaks every 20) – for example to equalise the axes of multiple plots displayed side-by-side – add `limits=c(0,100)` like so: `+ scale_y_continuous(limits=c(0,100), breaks=seq(0,100, by = 20))` – rvrvrv Jul 09 '15 at 10:44
  • 1
    How would you alter this if you wanted to use the y limit of the data instead of specifying it? I tried `+scale_y_continuous(breaks = seq(0, ylim(), by = 500` but the error says "no applicable method for 'limits' applied to an object of class NULL". My data frame is in long format. Thanks – JJGabe Jun 03 '20 at 18:51
  • 3
    @JJGabe `max_val <- max(your_variable)` and then `scale_y_continuous(breaks = seq(0, max_val, by = 500), limits=c(0, max_val))` – adibender Jun 04 '20 at 07:56