1

How can I add a geom_segment to my geom_point plot so that there is line from x-axis to the point?

Here is my dummy code:

library(grid);library(gridExtra);library(dplyr);library(ggplot2)

## Data
group1 <- seq(1, 10, 2); group2 <-  seq(1, 20, 3)
x = c(group1, group2)
mydf <- data.frame (X =x , Y = rnorm (length (x),5,1), 
                    groups = c(rep(1, length (group1)), rep(2, length(group2))))

## Plots
p1 <- ggplot(data=mydf[mydf$groups==1,],aes(x=X,y=Y))+
  geom_point(size=2)+
  theme_bw()

p2 <- ggplot(data=mydf[mydf$groups==2,],aes(x=X,y=Y))+
  geom_point(size=2)+
  theme_bw()

## Facetting
summ <- mydf %>% group_by(groups) %>% summarize(len=diff(range(X)))
summ$p <- summ$len/max(summ$len)
summ$q <- 1-summ$p

ng <- nullGrob()
grid.arrange(arrangeGrob(p1,ng,widths=summ[1,3:4]),
             arrangeGrob(p2,ng,widths=summ[2,3:4]))

And my plot: enter image description here

Thanks

Bade

0

1 Answer 1

2

From ?geom_segment we see the requried aesthetics are x, xend, y, yend, so we can use

ggplot(data=mydf[mydf$groups==1,],aes(x=X,y=Y))+
  geom_point(size=2)+
  theme_bw() +
  geom_segment(aes(x=X, y=-Inf, xend=X, yend = Y))
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I am not sure how I missed plotting them directly because I was using a "for" loop in past do that like this: for (i in abreaks){ p1 = p1+geom_segment(x=i,y=1,xend=i,yend=Inf,linetype = 3) }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.