Search code examples
rggplot2margin

Reduce empty space in ggplot2 donut chart


I tried hard, but could not find an answer on SO that helped in my case...

With the following code I create a donut chart in R using the ggplot2-package:

library(ggplot2)

test_data <- data.frame(Test = 1:4, Freq = c(0.1, 0.2, 0.3, 0.4))

ggplot(test_data, aes(x = 2, y = Freq, fill = Test)) +
  geom_bar(stat = "identity") +
  coord_polar(theta = "y", start = 0)+
  theme_void() +
  xlim(c(-1, 2.5)) +
  annotate(geom = "text", x = -1, y = 0, label = "Test", size = 60/.pt) +
  theme(legend.position = "none",
        plot.background = element_rect(color="red", linewidth = 2))

The resulting chart has much of empty white space around the actual plot. How can I reduce or crop this margin within R?

Plot with empty space


Solution

  • Try use plot.margin within theme to adjust as needed.

    library(ggplot2)
    
    test_data <- data.frame(Test = 1:4, Freq = c(0.1, 0.2, 0.3, 0.4))
    
    ggplot(test_data, aes(x = 2, y = Freq, fill = Test)) +
      geom_bar(stat = "identity") +
      coord_polar(theta = "y", start = 0) +
      theme_void() +
      xlim(c(-1, 2.5)) +
      annotate(geom = "text", x = -1, y = 0, label = "Test", size = 60/.pt) +
      theme(legend.position = "none",
            plot.background = element_rect(color = "red", linewidth = 2),
            plot.margin = margin(-1, -1, -1, -1, "cm")) # Try to adjust as needed