Home > OS >  How can I customise a paletter in ggplot with values that are not in the data?
How can I customise a paletter in ggplot with values that are not in the data?

Time:07-23

Let's say I have the following:

library(ggplot)
library(viridis)

df <- data.frame(x = c(10:15), y = c(20:25), z = c(8, 14, 15, 17, 18, 9))

  ggplot(df, aes(x = x, y = z))  
    geom_tile(aes(fill = z))  
    scale_fill_viridis(discrete = FALSE)  
    scale_y_continuous(limits = c(0, 60))  
    scale_x_continuous(limits = c(0, 60))  
    theme_classic()
 

I have other data frames with the same structure with the constraint that values in z are between 0 and 20, inclusive. How can I create a palette where values below 15 have the same colour and values 15, 16, 17, 18, 19 and 20 have different colours, regardless of whether they are in the data frame. For instance, the max value in df is 18, but for the palette should be 20.

CodePudding user response:

If you are looking for a continuous scale of colors rather than a discrete scale, you can use the limits argument to set fixed limits of 0-20 in your color mapping. If you want a single fixed color between zero and 15, then a gradient between 15 and 20 (as your question implies), you can use scale_fill_gradientn

library(ggplot2)

df <- data.frame(x = c(10:15), y = c(20:25), z = c(8, 14, 15, 17, 18, 9))

ggplot(df, aes(x = x, y = z))  
  geom_tile(aes(fill = z))  
  scale_fill_gradientn(values = c(0, 0.749999, 0.75, 0.75001, 1),
                       
                       colors = c('lightblue', 'lightblue',
                                  'green3', 'green3', 'red'),
                       limits = c(0, 20))  
  scale_y_continuous(limits = c(0, 60))  
  scale_x_continuous(limits = c(0, 60))  
  theme_classic()

enter image description here

  • Related