Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounded corners in ggplot2?

Tags:

r

ggplot2

themes

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

like image 824
Jon Harmon Avatar asked Jan 11 '18 04:01

Jon Harmon


2 Answers

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)

enter image description here

The same trick could be applied to the panel background, legend background, etc., if you wanted other aspects of the plot to be rounded.

like image 65
Claus Wilke Avatar answered Oct 03 '22 12:10

Claus Wilke


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)

like image 29
teunbrand Avatar answered Oct 03 '22 12:10

teunbrand