From a132727e9de06dc43828b53de0257aa3fb76b33d Mon Sep 17 00:00:00 2001 From: Kara Woo Date: Tue, 27 Oct 2020 20:39:55 -0700 Subject: [PATCH] Fix saving plots with no background (#4244) * If plot theme background is null, set to transparent when saving * Add test for svg with no background * Make checking for NULL background more concise with %||% --- R/save.r | 2 +- tests/testthat/test-ggsave.R | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/R/save.r b/R/save.r index 1bdd11381c..98bd10e99a 100644 --- a/R/save.r +++ b/R/save.r @@ -87,7 +87,7 @@ ggsave <- function(filename, plot = last_plot(), filename <- file.path(path, filename) } if (is_null(bg)) { - bg <- calc_element("plot.background", plot_theme(plot))$fill + bg <- calc_element("plot.background", plot_theme(plot))$fill %||% "transparent" } old_dev <- grDevices::dev.cur() dev(filename = filename, width = dim[1], height = dim[2], bg = bg, ...) diff --git a/tests/testthat/test-ggsave.R b/tests/testthat/test-ggsave.R index 491e8f5913..b4ee2cc4dc 100644 --- a/tests/testthat/test-ggsave.R +++ b/tests/testthat/test-ggsave.R @@ -44,6 +44,21 @@ test_that("ggsave uses theme background as image background", { expect_true(grepl("fill: #00CCCC", bg)) }) +test_that("ggsave can handle blank background", { + skip_if_not_installed("xml2") + + path <- tempfile() + on.exit(unlink(path)) + p <- ggplot(mtcars, aes(disp, mpg)) + + geom_point() + + theme(plot.background = element_blank()) + ggsave(path, p, device = "svg", width = 5, height = 5) + img <- xml2::read_xml(path) + bg <- as.character(xml2::xml_find_first(img, xpath = "d1:rect/@style")) + expect_true(grepl("fill: none", bg)) +}) + + # plot_dim --------------------------------------------------------------- test_that("guesses and informs if dim not specified", {