My goal is to create a pie-donut plot using webr PieDonut and save as a png or jpg. My issue is that the plot shows great with both pie and donut when displayed in r notebook, but once saved to file, the inner pie is missing. This is how it's displayed before saving to file:
This is how it it shows after saving to file:
I've tried saving different ways using different plots: png, pdf, cairo_pdf, tiff, etc. No luck. I tried adjusting transparency and changing the radius, plot sizes and even trying a different computer. After looking at the webr documentation and trying their examples, it also displayed great, but saved to file with the missing pie. It only saved properly when I right-click and save as from the Help tab in R Studio.
I tried plotly and sunburst, but they lack the explode option and several other features.
Any ideas are greatly appreciated!
Code:
library(webr)
# Create a new dataset
devices <- structure(
list(
device = structure(
c(1L, 1L, 2L, 2L, 3L, 3L),
.Label = c("Desktop", "Mobile", "Tablet"),
class = "factor"
),
browser = structure(
c(1L, 2L, 1L, 2L, 1L, 2L),
.Label = c("Chrome", "Safari"),
class = "factor"
),
share = c(60, 40, 80, 20, 50, 50)
),
.Names = c("device", "browser", "share"),
row.names = c(NA, -6L),
class = "data.frame"
)
# Create a Pie-Donut chart using webr library
finalpie <- PieDonut(devices, aes(x = device, y = browser, count = share),
explode = 2, explodeDonut = TRUE,
ratioByGroup = FALSE) +
theme(
plot.margin = margin(t = 20, r = 20, b = 20, l = 20), # Adjust margins around the chart
plot.background = element_rect(fill = "white"), # Set background to white
panel.background = element_rect(fill = "white") # Set panel background to white
)
ggsave("piedonut1.png", plot = finalpie, width = 10, height = 8, units = "in" )
The PieDonut
source contains the lines:
print(p1,vp=viewport(height=1,width=1))
print(p3,vp=viewport(height=1,width=1))
It prints the donut and pie plots, but does not actually return them. This means that your finalpie
object does not contain both. You can see if you try to print it that it only contains the outer ring. Hence the issue you're observing with ggsave()
, which will also occur if you try to save this object using any other method.
One way to address this is with grDevices::recordPlot()
to capture the current plot:
finalpie <- PieDonut(devices, aes(x = device, y = browser, count = share),
explode = 2, explodeDonut = TRUE,
ratioByGroup = FALSE
) + theme(
plot.margin = margin(t = 20, r = 20, b = 20, l = 20),
plot.background = element_rect(fill = "white"),
panel.background = element_rect(fill = "white")
)
recorded_plot <- recordPlot()
png("piedonut1.png", width = 10, height = 8, units = "in", res = 300)
replayPlot(recorded_plot)
dev.off()