I want to create some plots with transparent background so I can use them in a presentation without overlapping other elements. I did some research and found a way to create a transparent plot using the ggsave function. This worked well until I wanted to save a plot that have labels overlapping. What I want to do have is the zoomed version of the plot with transparent background. I couldn't find a solution for this problem. Can someone help me with this problem?
This is the plot with transparent background, but with overlapping labels: Plot1
This is the zoomed version with the labels in the correct location: Plot2
I want to have plot 2 with transparent backgorund.
I used the following code getting plot 1:
branche <- dataset %>%
filter(!is.na(branche)) %>%
ggplot(aes(x= "", fill = branche)) +
geom_bar(stat= "count", width = 1, color = "white") +
geom_text(aes(label = scales::percent(..count.. / sum(..count..))),
stat = "count", position = position_stack(vjust = 0.5), size = 10) +
coord_polar("y", start = 0, direction = -1) +
labs(fill ="") +
scale_fill_manual(labels = c("Industri", "Tjenesteytelse", "Handel", "Bygg og anlegg"),
values = c("dodgerblue", "steelblue1", "seagreen", "goldenrod4")) +
theme_void() +
theme(legend.text = element_text(size = 20),
plot.background = element_rect(fill = "transparent", color = NA))
branche
ggsave(branche, filename = "branche.png", bg = "transparent")
Greetings
Saving files in R is linked to the resolution and aspect ratio of your graphics device. To try this out and see for yourself:
ggsave()
to save it as a .png file. Make a note of the dimensions of the saved image (you should see a notice like Saving 8.24 x 5.07 in image
).ggsave()
command and note that the image dimensions are now different.Interesting to note: text doesn't exactly size the same way that other graphics do, so when adjusting the width and height, your text will seem to stay pretty much the same but everything else will seem to grow/shrink.
So I would say that the fix is to try different aspect ratios/image dimensions. Rather than resizing and saving, I would suggest you can pass different arguments to ggsave()
through height=
and width=
. So something like specifying:
ggsave(branche, filename = "branche1.png", bg = "transparent", width=5, height=8)
ggsave(branche, filename = "branche2.png", bg = "transparent", width=6, height=9)
... etc
You should be able to get your transparent one to look right. I can't help you much further without sharing the dataset and the code you also used to generate the non-transparent plot. If the ggplot()
code for the non-transparent plot is identical to the transparent one, then it's likely you had resized the window between the two and that's why you're seeing the different ratios.