Home > Blockchain >  Can I choose the fill based on the color?
Can I choose the fill based on the color?

Time:05-15

I have the following example data:

d <- data.frame(x = 1:3, y = 1:3, category = letters[1:3], p = c(TRUE, TRUE, FALSE))

I'd like to plot this coloring by category.

ggplot(d, aes(x, y, color = category)   geom_point(shape = "circle filled")

Then I'd like to make the fill:

  • the same as the category if p is TRUE
  • white otherwise
ggplot(d, aes(x, y, color = category, fill = ???)   geom_point(shape = "circle filled")

Has anyone any suggestions?

Could I

  • access the color scale results and then manipulate them?
  • calculate color and fill manually, but still have the same legend labels?

CodePudding user response:

You can use fill = after_scale(color) to assign the fill to the same value as the color scale. Using after_scale(ifelse(p, color, "white") should give you the optional white fill value instead.

The only minor snag is that the usual NSE we get inside aes doesn't work inside after_scale, so we need to use d$p instead of just p for the first argument of ifelse

ggplot(d, aes(x, y, color = category))  
  geom_point(aes(fill = after_scale(ifelse(d$p, color, "white"))),
             shape = "circle filled", size = 10)

enter image description here

  • Related