ggplot2问题与facets和关闭剪辑

时间:2016-12-09 17:30:36

标签: r ggplot2

过去可以通过关闭剪裁将文本放在绘图边距上。在ggplot2_2.2.0中,在使用构面的图中似乎不再可能(但如果没有使用构面,则仍然有效)。我发布了一个问题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)

1 个答案:

答案 0 :(得分:2)

似乎通过合并this pull request,现在可以使用ggplot2进行可配置的裁剪。

我认为您只需要在clip = "off"函数中添加coord_cartesian。这样一来,就可以解决因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


或者,正如我在Annotate outside plot area once in ggplot with facets中提到的,您可以使用cowplot::draw_label

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