Home > Mobile >  Conditionally formating colors of tile plot in ggplot2
Conditionally formating colors of tile plot in ggplot2

Time:11-20

I have the following chart generated using ggplot2. I would like to find out how to conditionally format the color of each tile according to the following color hex codes and Value specifications

#0a5d00 if Value > 2
#0eff00 if Value > 1 and < 2
#ece75f if Value > 0 and < 1
#e6cc00 if Value > -1 and < 0
#ff0000 if Value > -2 and < -1
#7b0000 if Value < -2
data <- structure(list(Date = structure(c(18993, 19024, 19052, 19083, 
19113, 19144, 19174, 19205, 19236, 19266), class = "Date"), Value = c(-3, 
-2, -1.5, -1, -0.5, 0, 0.5, 1, 2, 3)), class = c("tbl_df", "tbl", 
"data.frame"), row.names = c(NA, -10L))

library(tidyverse)

data %>% 
  ggplot(aes(Date, Value, fill = Value))  
  geom_tile()

CodePudding user response:

Update adding scale_identity() thanks to @Tanga94:

library(tidyverse)

data %>% 
  mutate(my_color = case_when(
     Value > 2 ~ "#0a5d00", 
     Value > 1 & Value < 2 ~ "#0eff00",
     Value > 0 & Value< 1 ~ "#ece75f",
     Value > -1 & Value < 0 ~ "#e6cc00",
     Value > -2 & Value< -1 ~ "#ff0000", 
     Value < -2 ~ "#7b0000", 
     TRUE ~ NA_character_
  )) %>% 
  ggplot(aes(Date, Value, fill = my_color))  
  geom_tile()  
  scale_fill_identity()

enter image description here

  • Related