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

hfi*_*sch 11 r ggplot2 facet-wrap

我正在尝试创建一个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))
Run Code Online (Sandbox Code Playgroud)

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

糟糕的情节

我想要"E"方面出现在所有其他情节上.有什么想法吗?我知道geom_vline,geom_hlinegeom_abline都将出现在所有的方面,但我不知道是什么让他们独特.

mne*_*nel 7

您已type='E'linedata.frame中指定.如果要在类型上使用此行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)
Run Code Online (Sandbox Code Playgroud)

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

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

两者都创造

在此输入图像描述


jlh*_*ard 5

您还可以使用 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)
Run Code Online (Sandbox Code Playgroud)

产生这个: