繁体   English   中英

将geom_line添加到R中facet_wrap图中的所有构面

[英]Adding a geom_line to all facets in a facet_wrap plot in R

我正在尝试创建一个facet_wrap图,将四条独立的线与一条共同的第五条线进行比较; 目标是让所有其他四个facet_wrap图上出现第五行。

这是我的最小代码:

library(ggplot2)

x    = c( 1,  3,  1,  3,  2,  4,  2,  4)
y    = c( 1,  3,  2,  4,  1,  3,  2,  4)
type = c("A","A","B","B","C","C","D","D")
data = data.frame(x,y,type)

x    = c( 4,  1)
y    = c( 1,  4)
type = c("E","E")
line = data.frame(x,y,type)

ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
geom_line(data = line, aes(x,y))

我希望将第五行添加为独立的data.frame允许我这样做,但它只是将其添加为第五个方面,如下图所示:

糟糕的情节

我想要“E”方面出现在所有其他情节上。 有什么想法吗? 我知道geom_vlinegeom_hlinegeom_abline都将出现在所有方面,但我不确定是什么让它们与众不同。

您已line data.frame中指定type='E' 如果要在A,B,C,D类型上使用此行,则创建一个data.frame ,其中包含要显示该行的类型

xl    = c( 4,  1)
yl    = c( 1,  4)
type =rep(LETTERS[1:4], each=2)
line2 = data.frame(x=xl,y=yl,type)

ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
   geom_line(data = line2)

您也可以使用annotate ,这意味着您不指定data.frame,而是直接传递x和y值

ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type) +
  annotate(geom='line', x=xl,y=yl)

两者都创造

在此输入图像描述

您还可以使用geom_abline(...),如下所示:

x    <-  c( 1,  3,  1,  3,  2,  4,  2,  4)
y    <-  c( 1,  3,  2,  4,  1,  3,  2,  4)
type <-  c("A","A","B","B","C","C","D","D")
data <-  data.frame(x,y,type)

int   <- c(5,5,5,5)
slope <- c(-1,-1,-1,-1)
type  <- c("A","B","C","D")
ref   <- data.frame(int, slope, type)
ggplot(data, aes(x,y)) + geom_line() + facet_wrap(~type, scales="free") +
  geom_abline(data = ref, aes(intercept=int, slope=slope), color="red", size=2)

产生这个:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM