Home > Back-end >  Access how many levels there are in scale/fill in ggplot2
Access how many levels there are in scale/fill in ggplot2

Time:08-30

I have a function (mine has different colours, this is an example

library(grDevices)
my_palette <- colorRampPalette(c("#FF0000", "#0000FF"))

I would like to write my own function analagous to scale_colour_viridis_d or scale_fill_viridis_d. The closest I have got is this:

scale_my_palette <- function(n) {
  scale_colour_manual(
    values = my_palette(n)
  )
}

Which works but requires the user to manually input the number of levels of colours to be calculated. Is there a way for me to access the number of levels there are in the colour or fill aesthetics so that I can automatically set that number?

Extra question: Is there a way for me to detect if one of these levels is NA and then assign that a grey colour and have the rest of the palette unaffected? This is basically can I detect if one of the entries is NA and which entry this is, I can probably work out the rest of the code with the answer to the first question.

Many Thanks!

CodePudding user response:

You can easily convert your palette function to a discrete scale object using ggplot2::discrete_scale. This is how scale_color_viridis_d works.

There is no need to count levels or use scale_color_manual, since mapping your colors uses your palette function directly.

my_palette <- colorRampPalette(c("#FF0000", "#0000FF"))

scale_my_palette <- function (...)  {
  discrete_scale('color', 'myscale', my_palette, ...)
}

ggplot(mtcars, aes(wt, mpg, color = factor(gear)))  
  geom_point(size = 3)  
  scale_my_palette(name = 'gear')  
  theme_minimal(base_size = 16)

enter image description here

  • Related