How to manually add a tick mark in ggplot2?

Viewed 44

I am quite new to the ggplot2 world in R, so I am trying to get familiar with the technicalities of plotting with ggplot2. In particular, I have a problem, which can be replicated by the following MWE:

ggplot(data.frame(x = c(1:10), y = c(1:10)), aes(x = c(1:10), y = c(1:10))) +
  geom_line() +
  geom_hline(aes(yintercept = 6), lty = 2)

This generates a simple graph of a diagonal line with a horizontal dashed line that cuts the y-axis at 6.

I would like to know whether there is a way to add a tick mark of 6 on the y-axis? In other words, say I simply showed this plot to a person without the code. I want the person to know that the horizontal dashed line cuts the y-axis at 6, which is not easily seen since 6 is not labelled currently.

Any intuitive suggestions will be greatly appreciated :)

2 Answers

You can use scale_y_continuous and give it all the points where you'd want a tick in the breaks argument.

library(ggplot2)
ggplot(data.frame(x = c(1:10), y = c(1:10)), aes(x = x, y = y)) +
  geom_line() +
  geom_hline(aes(yintercept = 6), lty = 2) + 
  scale_y_continuous(breaks = c(2, 4, 6, 8, 10))

in this specific example there is lots of "empty space" and you might consider adding the number within the plot using geom_text or geom_label if you think that is, what people should take away from your plot:

library(ggplot2)
ggplot(data.frame(x = c(1:10), y = c(1:10)), aes(x = x, y = y)) +
  geom_line() +
  geom_hline(aes(yintercept = 6), lty = 2) + 
  #scale_y_continuous(breaks = c(2, 4, 6, 8, 10)) +
  geom_label(aes(x=2, y=6, label = "line at y = 6.0"))
  

Your data frame

    df <- data.frame(x = c(1:10), y = c(1:10))
    
    #Plotting 
    p <- ggplot(df, aes(x, y)) + 
      geom_point() 
p

Custom function from here

It creates both x and y breaks

add_x_break <- function(plot, xval) {
  
  p2 <- ggplot_build(plot)
  breaks <- p2$layout$panel_params[[1]]$x$breaks
  breaks <- breaks[!is.na(breaks)]
  
  plot +
    geom_vline(xintercept = xval) +
    scale_x_continuous(breaks = sort(c(xval, breaks)))
}

add_y_break <- function(plot, yval) {
  
  p2 <- ggplot_build(plot)
  breaks <- p2$layout$panel_params[[1]]$y$breaks
  breaks <- breaks[!is.na(breaks)]
  
  plot +
    geom_hline(yintercept = yval) +
    scale_y_continuous(breaks = sort(c(yval, breaks)))
}

Define your break in your case y break

p <- add_y_break(p, 6)
p

Hope this helps

A bit of improvement with the ticks

p <- ggplot(df, aes(x, y)) + 
  geom_point()+
  scale_x_continuous(breaks = round(seq(min(df$x), max(df$x), by = 0.5),1)) +
  scale_y_continuous(breaks = round(seq(min(df$y), max(df$y), by = 0.5),1))

p

p <- add_y_break(p, 6)
p
Related