Transparent graphing for dark backgrounds

I’m not usually a dark background person but I’m open to the dark side. I wanted to make a solid coloured graph with a transparent background that would show up nicely but ggplot2 doesn’t have a set theme for that. A clean solid fill and transparency requires some specific customisation so here is a reproducible example for you using the built-in trees dataset:

tree_graph <- ggplot(data = trees, 
       mapping = aes(x = Height, 
                     y = Girth)) + 
    geom_point(size = 0.5, colour = "#B8DE29FF") + 
    geom_smooth(method = "lm", se = FALSE, col = "#B8DE29FF") + 
    geom_abline(intercept = 0, slope = 1, col = "white", lwd = 0.5, lty = 2) + 
    theme_classic() +
    theme(plot.background = element_rect(fill = "transparent", color = NA),
          panel.background = element_rect(fill = "transparent"),
          axis.text = element_text(colour = "#B8DE29FF", size = 8),
          axis.title = element_text(colour = "#B8DE29FF", size = 8),
          axis.line = element_line(colour = "#B8DE29FF"),
          axis.ticks = element_line(colour = "#B8DE29FF"))

ggsave(tree_graph, filename = "tree_graph.png", bg = "transparent", type = "cairo", width = 10, height = 10, dpi = 300)

There are a couple of generally useful elements added on purpose:

  • geom_smooth creates an automatically fitted linear model (defined using method = "lm"). I have turned off plotting the standard errors (on by default) and manually set the colour.
  • geom_abline is your standard straight line
  • theme is where the customisation begins:
    • plot.background & panel.background are set to transparent
    • The various axis elements are set to the fill colour (a nice viridis green) and desired text size
  • ggsave specifies that the background is transparent and to save it using the Cairo engine (type = "cairo"). Cairo will create a vector based image so resizing the png isn’t an issue since the small font size is already defined.
    • You can also use cairo-png but the graph height and width options appear to be ignored.
    • If you don’t save it as a Cairo png, then the text will still have a white outline and won’t be a clean solid fill
Avatar
Jacinta Kong
Postdoctoral Fellow

My research interests include species distributions, phenology & climate adaptation of ectotherms.

Next
Previous

Related