【问题标题】:ggplot: clipping lines between facetsggplot:切面之间的剪裁线
【发布时间】:2017-07-17 15:07:19
【问题描述】:

假设我有这样的情节:

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

现在,我想在条形所在的两个方面一直绘制线条。我添加这个:

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

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

# 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 &lt;- "off" 关闭所有可能的剪辑,但这并没有解决问题。)有解决方法吗?

【问题讨论】:

  • this answer 能满足您的需求吗?
  • 看起来确实像。谢谢!显然我今天的谷歌赋特别弱……
  • 实际上,该代码似乎不适用于我(或其他几个小时前发布的人)。其他人能成功运行吗?

标签: r ggplot2 facet-wrap


【解决方案1】:
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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-25
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2015-06-05
    相关资源
    最近更新 更多