ggplot:facet之间的剪切线

时间:2017-07-17 15:07:20

标签: r ggplot2 facet-wrap

说我有这样的情节:

# Load libraries
library(ggplot2)
library(grid)

# Load data
data(mtcars)

# Plot results
p <- ggplot(data = mtcars) 
p <- p + geom_bar(aes(cyl)) 
p <- p + coord_flip()
p <- p + facet_wrap(~am)

print(p)

enter image description here

现在,我想在条形图的两个面上绘制线条。我补充一点:

p <- p + geom_vline(aes(xintercept = cyl))

enter image description here

添加了线条,但它们不会跨越两个方面。因此,我尝试使用此解决方案关闭剪辑:

# Turn off clipping
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name == "panel"] <- "off"

# Plot results
grid.draw(gt)

但这并没有解决问题:线仍然被剪裁。所以,我想知道这是否特定于geom_vline并尝试使用geom_ablinegeom_line(后者的值超过±Inf),但结果是相同的。在其他帖子中,剪辑解决方案似乎适用于文本和点,但可能在这种情况下,线仅在图的限制内定义。 (我甚至尝试gt$layout$clip <- "off"关闭所有可能的剪辑,但这并没有解决问题。)是否有解决方法?

1 个答案:

答案 0 :(得分:0)

library(grid)
library(gtable)

# Starting from your plot `p`
gb <- ggplot_build(p)
g <- ggplot_gtable(gb)

# Get position of y-axis tick marks
ys <- gb$layout$panel_ranges[[1]][["y.major"]]


# Add segments at these positions
# subset `ys` if you only want to add a few
# have a look at g$layout for relevant `l` and `r` positions
g <- gtable_add_grob(g, segmentsGrob(y0=ys, y1=ys, 
                                     gp=gpar(col="red", lty="dashed")), 
                     t = 7, l = 4, r=8)

grid.newpage()
grid.draw(g)

请参阅ggplot, drawing multiple lines across facets了解如何重新调整值以进行更一般的绘图。即

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

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

g <- gtable_add_grob(g, segmentsGrob(y0=start, y1=start),
                      t=7, r=4, l=8)