How to change the plot.background in Donut ggplot graph?

645 Views Asked by At

How to change the plot.background in a 'geom_rect()' + 'coord.polar()' in a Donut ggplot graph?

I dont know what I´m missing, but I´w working in html black background style and needing to set panel as well plot background to black, but the graph sides of my ggplot are white and I need to know which attribute or command I need to use to turn sides to black too.

Below my code:

my_df %>% 
  ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
  geom_rect() +
  geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
  coord_polar(theta="y") +
  xlim(c(2, 4)) + 
  theme_void() +
  theme(legend.position="none", 
        plot.background=element_rect(fill = "black"),
        panel.background = element_rect(fill = "black"),
        panel.border = element_blank(),
        legend.key = element_blank(),
        axis.ticks = element_blank(),
        axis.text.y = element_blank(),
        panel.grid  = element_blank())

Below the resulted graph (see the "white" sides at right and left I need to fill with black)

enter image description here

1

There are 1 best solutions below

1
On

The problem here is that ggplot by default calls grid::grid.newpage before drawing. This creates a blank (white) screen. It will then set up a square viewport to fit your plotting window because you are using coord_polar. Once it has done this, it considers the square area to be "the" plotting window. In a sense then, ggplot has no knowledge or control over these white areas. No theme element can touch it.

The solution is to explicitly call grid.newpage yourself, draw a black background manually, and then explicitly print your ggplot using the parameter newpage = FALSE. You could alternatively set the grid gpar parameters so that the background is black by default, but this is likely to have undesired side effects later on.

Here's a reprex with some made-up data:

my_df <- data.frame(max = c(160, 320), min = c(0, 161), 
                    ResultCode = c("A","B"), 
                    labelPosition = c(80, 240), label = c("A", "B"))

p <- my_df %>% 
  ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
  geom_rect() +
  geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
  coord_polar(theta="y") +
  xlim(c(2, 4)) + 
  theme(legend.position="none", 
        plot.background =  element_rect(fill = "black", color = "black"),
        panel.background = element_rect(fill = "black", color = "black"),
        plot.margin = margin(0,0,0,0),
        panel.border = element_blank(),
        legend.key = element_blank(),
        axis.ticks = element_blank(),
        axis.text.y = element_blank(),
        panel.grid  = element_blank())

grid::grid.newpage()
grid::grid.draw(grid::rectGrob(gp = grid::gpar(fill = "black")))
print(p, newpage = FALSE)

enter image description here