0
votes

I'm trying to add a specific tick mark and label to an axis using ggplot2, without changing the rest of the axis or gridlines.

Let's say I have the following plot:

library(ggplot2)

d <- data.frame(x = c(0:100), y = c(0:100))

plot <- ggplot(d, aes(x = x, y = y)) + geom_point()
plot

enter image description here

What I would like to do is add a specific tick mark and value on the y axis, to indicate a cut-off point of some sort. In the actual implementation, this cutoff and the data are to plot arguments passed to a function, so I want to do this without hard coding the values.

I found a solution to add a specific tick mark + label to an axis here, which works correctly. Let's say in this case, I want to add it at y = 10. However, if I try it, the gridlines change as well:

plot + scale_y_continuous(breaks = c(pretty(d$y), 10),
                          labels = c(pretty(d$y), 10))

enter image description here

Notice that now, rather than having major gridlines every 25 units and minor gridlines every 12.5 units, there are now major gridlines every 20 units and minor gridlines every 10. In addition, for some mysterious reason, an extra minor gridline has been added at y = 55.

Is there a way I can add the tick + label for y = 10, while otherwise making the y axis look like the first plot? Ideally, the solution would still allow me to use the n.breaks argument when setting up the y axis as well, so that I could request some number of breaks, and then add the extra one to that.

2
Any particular reason why you want to have the reference line as part of the plot's grid, rather than a separate geom_hline(yintercept = <whatever desired value>) + annotated label?Z.Lin

2 Answers

1
votes

To use the method you wrote, you need to specify minor.breaks too.

plot + scale_y_continuous(breaks = c(pretty(d$y), 10),
                          labels = c(pretty(d$y), 10), 
                          minor_breaks = pretty(d$y, n = 2*length(pretty(d$y))))

enter image description here

0
votes

Usually much easier and clearer to have a cut-off point as a hline as Z.Lin suggested. As even if it is on the axis it would probably still need a hline to get the desired effect.

E.g.

library(ggplot2)

d <- data.frame(x = c(0:100), y = c(0:100))

plot <- ggplot(d, aes(x = x, y = y)) + geom_point()
plot

plot +
  geom_hline(yintercept = 10, linetype = "dotdash", size = 0.9, alpha = 0.5)+
  annotate(geom = "text",x = 80, y = 14, label = "Cut-off point", fontface = 'italic')