Search code examples
rggplot2plotdata-visualizationscatter-plot

R: Combining "vline" and "hline" statements together (ggplot2)


I am working with the R programming language. Recently, I learned how to "draw" horizontal and vertical lines with the ggplot library:

library(ggplot2)

# Simple scatter plot
sp <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()

# Add horizontal line at y = 2O

a = sp + geom_hline(yintercept=20) 

b = sp + geom_vline(xintercept = 3)

enter image description here

Now, I am trying to combine these statements together - for example:

c = sp + geom_hline(yintercept=20) +  geom_hline(yintercept=15) + geom_vline(xintercept = 3) +
    geom_vline(xintercept = 5) + geom_vline(xintercept = 6) + geom_hline(yintercept=35)

enter image description here

Question: I am trying to modify the above plot so that it looks like this:

enter image description here

Can someone please show me how to do this? Or do you have to manually export this plot into Microsoft Paint and change it over there?

Thanks


Solution

  • You could add a layer using annotate. Each segment is a matched element of the four vectors below. ie the first segment starts at (-Inf,15) and ends at (3,15).

    ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
      annotate("segment", 
               x = c(-Inf, 3, -Inf, 5, -Inf, 6),
               y = c(15, 15, 20, 20, 35, 35),
               xend = c(3, 3, 5, 5, 6, 6),
               yend = c(15, -Inf, 20, -Inf, 35, -Inf))
    

    enter image description here

    Or perhaps it would be easier to define a function which draws two lines from a point toward the axes (assuming here the point is positive so it should head toward -Inf). To make a function output multiple ggplot2 elements, put them in a list:

    draw_guides<- function(x, y) {
      list(geom_segment(aes(x = -Inf, xend = x, y = y, yend = y)),
           geom_segment(aes(x = x, xend = x, y = y, yend = -Inf)))
    }
    

    Then you can call each one to recreate the desired figure more easily:

    ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
      draw_guides(3,15) +
      draw_guides(5,20) +
      draw_guides(6,35)