Home > Net >  Plot scale gradient with a discrete cutoff in geom_tile()
Plot scale gradient with a discrete cutoff in geom_tile()

Time:03-19

Hi guys I have a sample data frame as such:

df = data.frame(sender = "Bob",
                receiver = c("Amy","James","Ronald","Andy","Harry","Mary"),
                frequency = c(0,1,2,3,5,10))

I want to plot it with geom_tile in this format:

df %>% ggplot(aes(x=sender,y=receiver,fill=frequency))   
  geom_tile(stat = "identity",position = "identity",colour = "black")    
  scale_fill_gradientn(colours = c("white","red")) 

Currently I'm using the scale_fill_gradientn to create the white to red gradient but is it possible to incorporate a cutoff where if the value was 0 it would be white and anything larger than 0 (aka starting from 1) it would already be red and then still keep having an increasing gradient as the frequency increases? I tried putting more colours into the colours argument but it cannot specify where the cutoff starts for the data, thanks a lot!

CodePudding user response:

You need to add values to assign the colours to values (on a normalized scale between 0 and 1)

ggplot(df, aes(sender, receiver, fill = frequency))   
  geom_tile(colour = "black")    
  scale_fill_gradientn(colours = c("white", "#FFA0A0", "red"),
                       values  = c(0, 0.001, 1))

enter image description here

CodePudding user response:

I suggest using scale_fill_gradient instead of scale_fill_gradientn. You specify your color for low values and high values and set limits from lowest to highest where you want the color step scheme to be applied. Assign a color for na.value, e.g. not within the set range for the color step scheme.

df %>% ggplot(aes(x=sender,y=receiver,fill=frequency))   
  geom_tile(stat = "identity",position = "identity",colour = "black")  
  scale_fill_gradient(low = "indianred2", high = "red",
                      limits = c(1, max(df$frequency)), na.value = "white")

enter image description here

CodePudding user response:

I reorder the y-axis so that you get a increasing gradient of red using the scale_fill_gradient function. You can use this code:

library(tidyverse)
df = data.frame(sender = "Bob",
                receiver = c("Amy","James","Ronald","Andy","Harry","Mary"),
                frequency = c(0,1,2,3,5,10))

df %>% ggplot(aes(x=sender,y=reorder(receiver, frequency),fill=frequency))   
  geom_tile(stat = "identity",position = "identity",colour = "black")    
  ylab("receiver")  
  scale_fill_gradient(low = "indianred2", high = "red", limits = c(1, 10), na.value = "white")

Output:

enter image description here

  • Related