Are there easy way to set limit of vertical or horizontal line in ggplot?

Viewed 5887

I want to plot part of geom_vline or geom_hline,codes as follows:

df <- data.frame(x=1:10,y=1:10)
plt <- ggplot(data=df)+
  geom_point(aes(x=x,y=y))+
  geom_vline(aes(xintercept=x[2]))+
  geom_hline(aes(yintercept=y[2]))

I expect to display the left and lower part line as the cross point. but there is no argument such as xlim or ylim in geom_vline

enter image description here

1 Answers

You can use geom_line.

library(ggplot2)

df <- data.frame(x=1:10,y=1:10)
plt <- ggplot(data=df)+
  geom_point(aes(x = x, y = y))+
  geom_line(data = data.frame(x = c(2, Inf), y = c(2, 2)), aes(x = x , y = y)) +
  geom_line(data = data.frame(x = c(2, 2), y = c(2, Inf)), aes(x = x, y = y)) 

Or geom_segment. They resulted in the same plot.

plt <- ggplot(data=df)+
  geom_point(aes(x = x, y = y))+
  geom_segment(aes(x = 2 , y = 2, xend = Inf, yend = 2)) +
  geom_segment(aes(x = 2 , y = 2, xend = 2, yend = Inf))

enter image description here

Related