Home > Net >  R: automatically assigning all colors
R: automatically assigning all colors

Time:07-18

I am working with the R programming language. I have this data:

letters = replicate(52, paste(sample(LETTERS, 10, replace=TRUE), collapse=""))
values = rnorm(52, 100, 100)

my_data = data.frame(letters, values)

I am trying to plot this data:

library(ggplot2)
library(waffle)

 waffle(my_data, size = 0.6, rows = 10)

But this gives me the error:

! Insufficient values in manual scale. 51 needed but only 8 provided.
Run `rlang::last_error()` to see where the error occurred.

Normally, I would have manually provided the colors - but 51 colors are a lot to insert manually. Is there some automatic way that can recognize how many colors are required and then fill them all in?

Thanks!

CodePudding user response:

You can use a vector of 53 colors using a palette function such as scales::hue_pal()(53) (note I have had to alter the way the input data is used, since your unmodified example data and code simply returns an error)

waffle(setNames(abs(round(my_data$values/10)), 
                my_data$letters), size = 0.6, rows = 10,
       colors = scales::hue_pal()(53))  
  theme(legend.position = "bottom")

enter image description here

The obvious caveat is that 53 discrete colors is far too many to have in a waffle plot. It is simply unintelligible from a data visualisation point of view. Whatever you are trying to demonstrate, there will certainly be a better way to do it than a waffle chart with 53 discrete colors.

  • Related