8

I have a faceted graph with a strip label which is clipped due to the width of the facets - I have been removing this clip manually in Inkscape but would like to do it in R. See this small reproducible example (the figure width is non-negotiable and needs to be exported as a .eps file):

library(tidyverse)

# Build data frame
df <- data.frame(treatment = factor(c(rep("A small label", 5), rep("A slightly too long label", 5))),
             var1 = c(1, 4, 5, 7, 2, 8, 9, 1, 4, 7),
             var2 = c(2, 8, 11, 13, 4, 10, 11, 2, 6, 10))

# Plot scatter graph with faceting by 'treatment'
p <- ggplot(df, aes(x = var1, y = var2)) + 
  geom_point() + 
  facet_wrap(treatment ~ ., ncol = 2)

# Save graph as .eps
ggsave(filename = "Graph1.eps", plot = p, device = "eps", width = 60, height = 60, units = "mm")

A scatter plot with clipped facet labels

What I would like is this, where the facet label extends beyond the width of the facet:

A scatter plot with the clip removed from the facet label

So far I've tried the following from this StackOverflow question:

# This doesn't affect the strip labels
p2 <- p +
  coord_cartesian(clip = "off")

ggsave(filename = "Graph.eps", plot = p2, device = "eps", width = 60, height = 60, units = "mm")

# This doesn't affect strip labels and results in a blank white graph when exported using ggsave
p3 <- p
p3$layout$clip = "off"

ggsave(filename = "Graph.eps", plot = p3, device = "eps", width = 60, height = 60, units = "mm")

I also tried this way of turning the layout$clip off from this question but it has the same issues as above with the strip labels still being clipped and ggsave exporting a blank file.

p4 <- ggplot_gtable(ggplot_build(p))
p4$layout$clip[p4$layout$name == "panel"] <- "off"
p4 <- grid.draw(p4)

ggsave(filename = "Graph.eps", plot = p4, device = "eps", width = 60, height = 60, units = "mm")

Lucy Wheeler
  • 271
  • 3
  • 17

1 Answers1

9

EDIT: As of ggplot2 3.4.0, this has been integrated.

There is a feature request with an open PR on the ggplot2 github to make strip clipping optional (disclaimer: I filed the issue and opened the PR). Hopefully, the ggplot2 team will approve it for their next version.

In the meantime you could download the PR from github and try it out.

library(ggplot2) # remotes::install_github("tidyverse/ggplot2#4223")

df <- data.frame(treatment = factor(c(rep("A small label", 5), rep("A slightly too long label", 5))),
                 var1 = c(1, 4, 5, 7, 2, 8, 9, 1, 4, 7),
                 var2 = c(2, 8, 11, 13, 4, 10, 11, 2, 6, 10))

# Plot scatter graph with faceting by 'treatment'
p <- ggplot(df, aes(x = var1, y = var2)) + 
  geom_point() + 
  facet_wrap(treatment ~ ., ncol = 2) +
  theme(strip.clip = "off")

ggsave(filename = "Graph1.eps", plot = p, device = "eps", width = 60, height = 60, units = "mm")

enter image description here

teunbrand
  • 33,645
  • 4
  • 37
  • 63