【问题标题】:Adding a geom_line to all facets in a facet_wrap plot in R将 geom_line 添加到 R 中 facet_wrap 图中的所有方面
【发布时间】:2013-12-21 17:03:46
【问题描述】:

我正在尝试创建一个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 都会出现在所有方面,但我不确定是什么让它们与众不同。

【问题讨论】:

    标签: r ggplot2 facet-wrap


    【解决方案1】:

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

    两者都创建

    【讨论】:

    • 您甚至可以完全省略类型列,即line2 = data.frame(x=xl,y=yl)。这条线在所有面板上都是相同的,然后...
    • 我也有同样的问题,但这个解决方案不再有效:“错误:您将函数作为全局数据传递。您是否拼错了 ggplot() 中的 data 参数”
    • 这仍然对我有用,所以@AdrianMartin 一定是在他无法使其工作时偶然发现了一些其他问题。
    【解决方案2】:

    您也可以按如下方式使用 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)
    

    这会产生:

    【讨论】:

    • 我可能让我的可重现示例有点太简单了;我的实际代码实际上不止两点。我应该添加第三点来说明我的问题。无论如何,您的回答肯定解决了我提交的问题。
    猜你喜欢
    • 1970-01-01
    • 2016-08-11
    • 2014-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多