ggplot2 issue with facets and turning off clipping

流过昼夜 提交于 2021-02-20 06:24:43

问题


It used to be possible to put text on plot margins by turning off clipping. In ggplot2_2.2.0 this doesn't seem to be possible anymore in plots that use facets (but still works if no facets are used). I've posted an issue here but it has not been addressed yet. Any ideas for workarounds in the meantime would be greatly appreciated!

Here is a minimal (non-)working example:

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:


It seems that with merging this pull request, it is possible now to have configurable clipping with ggplot2.

I think you just need to add clip = "off" in the coord_cartesian function. So that should solve the need of doing gt = ggplot_gtable(ggplot_build(p)) fallowed by gt$layout$clip = "off".

That is, this should suffice (tested with ggplot2 version 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"))


Alternatively, as I mentioned in Annotate outside plot area once in ggplot with facets, you can make use of cowplot::draw_label:

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



来源:https://stackoverflow.com/questions/41065829/ggplot2-issue-with-facets-and-turning-off-clipping

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!