将geom_segment添加到ggplot中的geom_point图中 [英] Add geom_segment to geom_point plot in ggplot
本文介绍了将geom_segment添加到ggplot中的geom_point图中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将geom_segment添加到我的geom_point图中,以便从x轴到点的线?
以下是我的虚拟代码:
library(grid); library(gridExtra); library(dplyr); library(ggplot2)
##数据
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()
##构面
summ< - mydf%>%group_by(groups)%>%汇总(len = diff(范围(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]))
我的情节:
谢谢s
解决方案
geom_segment 我们看到需要的美学是 x
, xend
, y
, yend
,所以我们可以使用
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))
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:
Thanks
Bade
解决方案
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))
这篇关于将geom_segment添加到ggplot中的geom_point图中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文