Skip to content

Commit a132727

Browse files
authored
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 %||%
1 parent 7e51849 commit a132727

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

R/save.r

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ ggsave <- function(filename, plot = last_plot(),
8787
filename <- file.path(path, filename)
8888
}
8989
if (is_null(bg)) {
90-
bg <- calc_element("plot.background", plot_theme(plot))$fill
90+
bg <- calc_element("plot.background", plot_theme(plot))$fill %||% "transparent"
9191
}
9292
old_dev <- grDevices::dev.cur()
9393
dev(filename = filename, width = dim[1], height = dim[2], bg = bg, ...)

tests/testthat/test-ggsave.R

+15
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,21 @@ test_that("ggsave uses theme background as image background", {
4444
expect_true(grepl("fill: #00CCCC", bg))
4545
})
4646

47+
test_that("ggsave can handle blank background", {
48+
skip_if_not_installed("xml2")
49+
50+
path <- tempfile()
51+
on.exit(unlink(path))
52+
p <- ggplot(mtcars, aes(disp, mpg)) +
53+
geom_point() +
54+
theme(plot.background = element_blank())
55+
ggsave(path, p, device = "svg", width = 5, height = 5)
56+
img <- xml2::read_xml(path)
57+
bg <- as.character(xml2::xml_find_first(img, xpath = "d1:rect/@style"))
58+
expect_true(grepl("fill: none", bg))
59+
})
60+
61+
4762
# plot_dim ---------------------------------------------------------------
4863

4964
test_that("guesses and informs if dim not specified", {

0 commit comments

Comments
 (0)