Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add a label to the x / y axis whenever a vertical / horizontal line is added to a ggplot?

The x and y axis are labeled based on certain interval set by ggplot.

In the event that a horizontal or vertical line is added to the plot, the goal is to label x or y axis at the exact value of the line.

How can this be done?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This isn’t totally straightforward, but it is possible. I would probably use these two little functions to automate the tricky parts:

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)))
}

These would work like this. Start with a basic plot:

library(ggplot2)

set.seed(1)

df <- data.frame(x = 1:10, y = runif(10))

p <- ggplot(df, aes(x, y)) + 
  geom_point() +
  ylim(0, 1)

p

Add a vertical line with add_x_break

p <- add_x_break(p, 6.34)

p

Add a horizontal line with add_y_break:

p <- add_y_break(p, 0.333)
#> Scale for 'y' is already present. Adding another scale for 'y', which will
#> replace the existing scale.

p

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading