ggplot2问题与方面和关闭剪辑 [英] ggplot2 issue with facets and turning off clipping

查看:20
本文介绍了ggplot2问题与方面和关闭剪辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去,可以通过关闭裁剪功能在图边距上放置文本.在ggplot2_2.2.0中,在使用构面的图中似乎不再可行(但如果不使用构面,则仍然可行).我在


或者,正如我在在ggplot中用构面注释一次绘制外部绘图区域一样,您可以使用 cowplot :: draw_label :

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

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)

解决方案

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)

这篇关于ggplot2问题与方面和关闭剪辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆