【问题标题】:ggplot, drawing multiple lines across facetsggplot,在各个方面绘制多条线
【发布时间】:2017-02-10 05:05:07
【问题描述】:

我使用 ggplot2 facet 在一个列中绘制了两个面板,并想在 x = 4 和 8 处在面板上添加两条垂直线。以下是代码:

library(ggplot2)
library(gtable)
library(grid)

dat <- data.frame(x=rep(1:10,2),y=1:20+rnorm(20),z=c(rep("A",10),rep("B",10)))

P <- ggplot(dat,aes(x,y)) + geom_point() + facet_grid(z~.) + xlim(0,10)
Pb <- ggplot_build(P);Pg <- ggplot_gtable(Pb)

for (i in c(4,8)){
    Pg <- gtable_add_grob(Pg, moveToGrob(i/10,0),t=8,l=4)
    Pg <- gtable_add_grob(Pg, lineToGrob(i/10,1),t=6,l=4)
}

Pg$layout$clip <- "off"
grid.newpage()
grid.draw(Pg)

以上代码修改自:ggplot, drawing line between points across facets。 还有。

这个图有两个问题。首先,只显示了一条垂直线。 moveToGrob 似乎只工作了一次。其次,显示的行在 x = 4 处不准确。我没有找到 Pb$panel$ranges 变量,那么有没有办法也可以更正范围?非常感谢。

【问题讨论】:

  • ggplot(dat,aes(x,y)) + geom_point() + facet_grid(z~.) + xlim(0,10) + geom_vline(xintercept = c(4, 8))
  • @alistaire 也许您应该将此添加为答案,因为您的解决方案应该修复/回答 OP。

标签: r ggplot2


【解决方案1】:

更新到ggplot2 V3.0.0

在面板具有公共轴并且线条延伸到整个 y 范围的简单场景中,您可以在整个 gtable 单元格上绘制线条,找到正确的 npc 坐标转换(参见以前的帖子,因为 ggplot2 不断变化而更新),

library(ggplot2)
library(gtable)
library(grid)

dat <- data.frame(x=rep(1:10,2),y=1:20+rnorm(20),z=c(rep("A",10),rep("B",10)))

p <- ggplot(dat,aes(x,y)) + geom_point() + facet_grid(z~.) + xlim(0,10)
pb <- ggplot_build(p)
pg <- ggplot_gtable(pb)


data2npc <- function(x, panel = 1L, axis = "x") {
  range <- pb$layout$panel_params[[panel]][[paste0(axis,".range")]]
  scales::rescale(c(range, x), c(0,1))[-c(1,2)]
}


start <- sapply(c(4,8), data2npc, panel=1, axis="x")

pg <- gtable_add_grob(pg, segmentsGrob(x0=start, x1=start, y0=0, y1=1, gp=gpar(lty=2)), t=7, b=9, l=5)

grid.newpage()
grid.draw(pg)

【讨论】:

  • 再次,抱歉打扰,我无法完成这项工作,这是过时的吗? “R 版本 3.4.1,gtable_0.2.0,ggplot2_2.2.1”。 This post led me here.
【解决方案2】:

您可以只使用geom_vline 并完全避免grid 混乱:

ggplot(dat, aes(x, y)) + 
    geom_point() + 
    geom_vline(xintercept = c(4, 8)) + 
    facet_grid(z ~ .) + 
    xlim(0, 10)

【讨论】:

  • 谢谢阿利斯泰尔。甜菜根是正确的,我想要两条连续的线穿过各个方面..
猜你喜欢
  • 1970-01-01
  • 2019-10-20
  • 2021-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多