简体   繁体   English

ggplot:构面之间的剪切线

[英]ggplot: clipping lines between facets

Say I have a plot like this: 说我有这样的情节:

# 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)

在此处输入图片说明

Now, I want to plot lines all the way across both facets where the bars are. 现在,我想在条形图所在的两个面上绘制线条。 I add this: 我添加以下内容:

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

在此处输入图片说明

which adds the lines, but they don't cross both facets. 这会增加线条,但它们不会同时穿过两个方面。 So, I try to turn off clipping using this solution: 因此,我尝试使用以下解决方案关闭剪辑:

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

# Plot results
grid.draw(gt)

but that doesn't solve the problem: the lines are still clipped. 但这并不能解决问题:线条仍被剪切。 So, I wondered if this is specific to geom_vline and tried approaches with geom_abline and geom_line (the latter with values across ±Inf), but the results are the same. 因此,我想知道这是否特定于geom_vline并尝试使用geom_ablinegeom_line (后者的值跨±Inf)的方法,但是结果是相同的。 In other posts, the clipping solution seems to work for text and points, but presumably in this case the lines are only defined within the limits of the figure. 在其他帖子中,剪裁解决方案似乎适用于文本和点,但是大概在这种情况下,线条仅在图的范围内定义。 (I even tried gt$layout$clip <- "off" to switch off all possible clipping, but that didn't solve the problem.) Is there a workaround? (我什至尝试过gt$layout$clip <- "off"来关闭所有可能的裁剪,但这并不能解决问题。)是否有解决方法?

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)

see ggplot, drawing multiple lines across facets for how to rescale values for more general plotting. 请参阅ggplot,在各个构面上绘制多条线以了解如何重新调整值以进行更一般的绘制。 ie

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM