Ggplot2 plot background with rounded corners

With ggplot2 and the theme() function we can change the graph theme settings with almost any setting we like. See:

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.

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?


1 Like

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:

1 Like

Yeah, definitely sounds like a layout/extension situation.

@hoog10hk, you can see some existing ggplot2 extensions here:

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

@ClausWilke posted this solution on SO


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