rggplot2ggforce

How do I change the fill of individual circles in ggforce::geom_circle to custom hex code colors?


For the following geom_circle() example:

library(ggplot2)
library(ggforce)
circles <- data.frame(
  x0 = rep(1:3, 3),
  y0 = rep(1:3, each = 3),
  r = seq(0.1, 1, length.out = 9)
)

plt <- ggplot() +
  geom_circle(aes(x0 = x0, y0 = y0, r = r), data = circles)
plt

It correctly produces the following plot:

I wanted to fill the individual circles based on a vector of hex codes, for example colors <- rep("#00FF00",9)

However, when trying to manipulate the coloring with the following code:

colors <- rep("#00FF00",9)
ggplot() +
   geom_circle(aes(x0 = x0, y0 = y0, r = r), fill = colors, data = circles)

It produces the following error:

Error in `geom_circle()`:
! Problem while setting up geom aesthetics.
ℹ Error occurred in the 1st layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (3249)
✖ Fix the following mappings: `fill`

The number of circles is clearly 9, so I'm assuming that the actual geom_circle() transforms the input into a bunch of smaller datapoints or something like that. In any case, how would one go about transforming the colors individually? A potential solution is to iteratively add each circle individually but in my usecase there are thousands of circles that need to be added.


Solution

  • One option would be to add you colors as a column to your dataset which could be mapped on the fill aes and by adding scale_fill_identity.

    library(ggplot2)
    library(ggforce)
    
    circles$colors <- rep("#00FF00", 9)
    
    ggplot() +
      geom_circle(aes(x0 = x0, y0 = y0, r = r, fill = colors), data = circles) +
      scale_fill_identity() +
      coord_fixed()
    

    enter image description here