Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 issue with facets and turning off clipping

Tags:

r

ggplot2

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)
like image 739
Tobi Avatar asked Dec 09 '16 17:12

Tobi


1 Answers

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"))

enter image description here


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)

like image 188
Valentin Avatar answered Oct 17 '22 10:10

Valentin