This feels like it has to be possible, but I cannot figure out if I can do it relatively simply in a theme()
or have to dig deeper.
I would like to round the corners on the plot areas of my ggplot2
plots. How would I go about doing that?
Question inspired by: https://twitter.com/Hoog10HK/status/951305194809143296
You can replace the background grob with a round rectangle:
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)
The same trick could be applied to the panel background, legend background, etc., if you wanted other aspects of the plot to be rounded.
Thanks to theme element subclassing in ggplot2 v3.0.0, I was able to implement a more general approach in a github package with elementalist::element_rect_round()
. (disclaimer: I wrote that github package)
library(ggplot2)
library(elementalist) # devtools::install_github("teunbrand/elementalist")
ggplot(mtcars, aes(wt, mpg, colour = factor(cyl))) +
geom_point() +
facet_grid(~ cyl) +
theme(
legend.background = element_rect_round(radius = unit(0.2, "snpc")),
legend.key = element_rect_round(radius = unit(0.4, "snpc")),
panel.background = element_rect_round(radius = unit(1, "cm")),
strip.background = element_rect_round(radius = unit(8, "pt")),
plot.background = element_rect_round(fill = "#C4E7FF")
)
Created on 2021-07-05 by the reprex package (v1.0.0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With