过去可以通过关闭剪裁将文本放在绘图边距上.在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)
最佳答案 似乎合并
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"))
或者,正如我在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)