ggplot2中facets和关闭裁剪的问题

9
在 ggplot2_2.2.0 中,以前可以通过关闭剪切来在绘图边缘放置文本。但是,在使用 facets 的情况下,这似乎不再可能(但如果没有使用 facets,则仍然有效)。我在这里发布了一个问题here,但尚未解决。同时,如果有任何解决方法,请告知!以下是一个最小的(非)工作示例:
library(ggplot2)
library(grid)

df.plot = data.frame(x = 1, y = 1, facet = 'facet', stringsAsFactors = F)
df.text = data.frame(x = 1, y = -0.3, label = 'test', facet = 'facet', stringsAsFactors = F)

p = ggplot(df.plot,aes(x = x, y = y))+
  facet_grid(~facet)+ # 'test' is only printed outside of the plot if faceting is turned off
  geom_point()+
  geom_text(data = df.text,aes(x=x,y=y,label=label))+
  coord_cartesian(xlim = c(0, 2),ylim=c(0,2),expand=F)+
  theme(plot.margin=unit(c(2,2,2,2),"cm"))
gt = ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] = "off"
grid.draw(gt)

gt$layout$clip[gt$layout$name=="panel-1-1"] = "off" - hrbrmstr
太好了,这将删除第一个面板的剪辑。要删除所有剪辑,请使用以下代码:gt$layout$clip = "off" - Tobi
1个回答

7

看起来通过合并 this pull request,现在可以在 ggplot2 中进行可配置的裁剪。

我认为你只需要在 coord_cartesian 函数中添加 clip = "off"。这样就可以解决需要执行 gt = ggplot_gtable(ggplot_build(p)) 然后执行 gt$layout$clip = "off" 的需求。

也就是说,这应该就足够了(使用 ggplot2 版本 3.1.0 进行测试):

p = ggplot(df.plot,aes(x = x, y = y))+
  facet_grid(~facet)+
  geom_point()+
  geom_text(data = df.text,aes(x=x,y=y,label=label))+
  coord_cartesian(xlim = c(0, 2),ylim=c(0,2),expand=F, clip = "off")+ # added clip = "off"
  theme(plot.margin=unit(c(2,2,2,2),"cm"))

enter image description here


另外,正如我在使用ggplot中的facet注释图形区域外部一次中提到的那样,您可以利用cowplot::draw_label

cowplot::ggdraw(p) + cowplot::draw_label("test", x = 0.53, y = 0.13)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接