'R - gganimate won't fill in rectangles that overlap

I've made a tree map using a sequence of random numbers:

Tree Map

The square gets subdivided into a random amount of rectangles. Those rectangles then get subdivided in the same way, and so on. Each rectangle can either be red, blue, yellow, white or transparent, and this is decided randomly as well.

I wanted to make an animation showing each rectangle getting added one by one using transition_reveal(). Everything works fine, except for the fact that gganimate won't fill in any rectangles that are on top of a rectangle that's already been filled in. The borders get plotted, but nothing gets filled:

Incorrect Tree Map

Here's the code:

g = ggplot() + coord_cartesian(xlim = c(0,10), ylim = c(0,10), expand = FALSE) +
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = id, group = id), 
                colour = NA, data = df) + 
  geom_rect(aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, size = widths, group = id),
                colour = "black", fill = NA, data = df) +
  scale_fill_gradientn(colours = cols, guide = "none") +  
  scale_size_identity() +
  theme_void() + 
  theme(legend.position = "none")

g = g + transition_reveal(id)
b = animate(g, renderer = av_renderer(), width = 1080, height = 1080, res = 100, nframes = frames)
anim_save(filename = output, path = path, animation = b)

I've had to plot the borders and the colours separately.

Is it possible to have all the rectangles filled in during the animation, and why is this happening in the first place?

Thank you for your help.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source