将geom_segment添加到ggplot中的geom_point图

时间:2016-01-31 06:54:18

标签: r plot ggplot2

如何将geom_segment添加到我的geom_point图中,以便从x轴到该点有一条线?

这是我的虚拟代码:

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

我的情节: enter image description here

由于

Bade的

1 个答案:

答案 0 :(得分:2)

?geom_segment我们看到所要求的美学是xxendyyend,所以我们可以使用

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