# Combining "vline" and "hline" statements together

Recently, I learned how to "draw" horizontal and vertical lines with the ggplot2 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)
``````

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

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

[

]

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

Here is one solution.

``````library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.5

LINES <- data.frame(Startx=c(1,1,1,3,5,6),#horiz lines then vert lines
Starty=c(15,20,35,7,7,7),
Endx=c(3,5,6,3,5,6),
Endy=c(15,20,35,15,20,35))
ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()+
geom_segment(aes(x=Startx,y=Starty,xend=Endx,yend=Endy),data=LINES)+
coord_cartesian(ylim=c(9,36),xlim = c(1.5,6.2))#set limits tighter than line ends
`````` Created on 2021-08-14 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.