【问题标题】:Create line across multiple plots in ggplot2在 ggplot2 中跨多个图创建线
【发布时间】:2020-06-04 20:47:53
【问题描述】:

我想创建一条横穿两个地块的水平线,并结合拼凑包。

library(ggplot2)
library(patchwork)

# Annotation after plot
p1 <- ggplot(mtcars, aes(x=disp,y=mpg))+
  geom_point()
p2 <- ggplot(mtcars, aes(x=hp,y=mpg))+
  geom_point()
# Want line across plots at y (mpg) of 15
p3 <- (p1+p2)+annotate("segment",x=-Inf,xend=Inf,y=15,yend=15)
p3

此方法仅将线穿过最后一个图 (p2)。

尝试在每个绘图中添加注释。

# Annotation with each plot
p1 <- ggplot(mtcars, aes(x=disp,y=mpg))+
  geom_point()+
  annotate("segment",x=-Inf,xend=Inf,y=15,yend=15)
p2 <- ggplot(mtcars, aes(x=hp,y=mpg))+
  geom_point()+
  annotate("segment",x=-Inf,xend=Inf,y=15,yend=15)

p1+p2

此方法将线放在每个图上,但不在两者之间。

我想要这样的东西:

【问题讨论】:

    标签: r ggplot2 annotate patchwork


    【解决方案1】:

    您可以使用grid.draw 绘制线条,它将线条绘制在绘图窗口中的任何其他内容上:

    library(grid)
    p3
    grid.draw(linesGrob(x = unit(c(0.06, 0.98), "npc"), y = unit(c(0.277, 0.277), "npc")))
    

    但是,这里有一些注意事项。线条的确切位置由您决定,尽管如果您要经常执行此操作,则可以通过编程方式进行定位,但一次性调整 x 和 y 值以获得线条会更快你想要它的地方,就像我在一分钟内完成的那样。

    第二个需要注意的是,线定位在 npc 空间中,而 ggplot 使用了固定和灵活间距的组合。这样做的结果是,只要调整绘图的大小,线条就会相对于绘图移动。同样,这可以通过编程方式修复。如果你真的想打开那罐蠕虫,你可以在我对this question的回答中看到一个类似的解决方案@

    【讨论】:

      【解决方案2】:

      我喜欢@Allan 的回答,但这是使用facet_wrap 的另一种方法。

      首先,我们需要将数据转置更长的时间,以便它可以使用facet_wrap。然后黑客开始了。首先,我们需要使用strip.position = 'bottom' 将刻面条标签移动到下方。然后我们可以使用coord_cartesian(clip = 'off') 关闭剪裁,以便在图形区域之外绘制线条。接下来我们修复xlim,这样当您尝试在图形区域之外绘制线段时,图形绘制区域不会改变。

      最后,大技巧,你用新数据绘制geom_segment,所以它只绘制一个方面。您在调用geom_segment 中创建了一个新的data.frame,其数据使其绘制在要渲染的最后一个面板中,因此该行位于顶部。

      最后,在theme() 中进行了一些更改,因此条形背景为空白,并且位置位于轴刻度之外。

      library(ggplot2)
      library(dplyr)
      library(tidyr)
      ggplot(pivot_longer(mtcars, -mpg) %>% filter(name %in% c("disp", "hp")),
             aes(x=value, y=mpg, group=name)) +
        geom_point() + 
        facet_wrap(.~name, strip.position = "bottom") + 
        geom_segment(data = data.frame(mpg = 15, name = "hp"),
                     x=-650, xend=525, y=15, yend=15) +
        coord_cartesian(clip = 'off', xlim = c(0,500)) +
        theme(aspect.ratio = 1,
              strip.background = element_blank(),
              strip.placement = "outside") +
        labs(x = "") 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多