Ggplot2 plot background with rounded corners

ggplot2

#1

With ggplot2 and the theme() function we can change the graph theme settings with almost any setting we like. See: http://ggplot2.tidyverse.org/reference/theme.html

When we specifically look at plot.background within the theme setting, we can set the parameters with element_rect(), providing us with the tools to change colour, fill, etc.
See: http://ggplot2.tidyverse.org/reference/element.html

However, I’m not sure how to set the parameters such that I can have rounded corners for the plot background

Any tips on achieving this?

Thanks,


#2

I’ve been discussing this with someone on SO after they saw your tweet! Others might have more useful advice, but we speculated that this would probably require a ggplot2 extension that modified element_rect to include a roundedness parameter and allow for the use of grid.roundrect instead of grid.rect where roundedness was given by a user (assuming a default of zero).

In other words, not presently possible but doable with work :slightly_smiling_face:


#3

Yeah, definitely sounds like a layout/extension situation.

@hoog10hk, you can see some existing ggplot2 extensions here:
http://www.ggplot2-exts.org/

The Extending ggplot2 vignette is probably a good place to start as far as making your own extension goes.


#4

@ClausWilke posted this solution on SO

library(ggplot2)
library(grid)

# make a plot with blue background
p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() +
  theme(plot.background = element_rect(fill = "#C4E7FF"),
        panel.background = element_blank(),
        plot.margin = margin(20, 20, 20, 20))

# switch out background grob
g <- ggplotGrob(p)
bg <- g$grobs[[1]]
round_bg <- roundrectGrob(x=bg$x, y=bg$y, width=bg$width, height=bg$height,
                          r=unit(0.1, "snpc"),
                          just=bg$just, name=bg$name, gp=bg$gp, vp=bg$vp)
g$grobs[[1]] <- round_bg

# draw both plots side by side
cowplot::plot_grid(p, g, labels = c("rectangular", "rounded"),
                   scale = 0.85, hjust = 0.5, label_x = 0.5)