Home > Enterprise >  how to overlap factor(binary) & continuous variables in heat map in R
how to overlap factor(binary) & continuous variables in heat map in R

Time:03-22

The code below is adapted from enter image description here

Option 2

You can use scale_color_manual. Just ensure your Vaccine column is genuinely a factor variable with levels "0" and "1"

dat %>% mutate(state = reorder(state, desc(state))) %>%
  ggplot(aes(year, state, fill = rate))  
  geom_tile(aes(color = Vaccine), size = 0.35)  
  scale_color_manual(values = c('0' = "white", '1' = "pink"))  
  scale_x_continuous(expand = c(0,0))  
  scale_fill_gradientn(colors = jet.colors(16), na.value = 'white')  
  geom_vline(xintercept = 1963, col = "black")  
  theme_minimal()   
  theme(panel.grid = element_blank())  
  coord_cartesian(clip = 'off')  
  ggtitle(the_disease)  
  ylab("")  
  xlab("")    
  theme(legend.position = "bottom", text = element_text(size = 8))   
  annotate(geom = "text", x = 1963, y = 50.5, label = "Vaccine introduced", 
           size = 3, hjust = 0)  
  guides(color = guide_legend(override.aes = list(fill = "white")))

enter image description here

For what it's worth, I prefer option 1


Update

If you want multiple vaccine starting points you can do this too:

dat %>% mutate(state = reorder(state, desc(state))) %>%
  ggplot(aes(year, state, fill = rate))  
  geom_tile(color = "white", size = 0.35)  
  annotate("rect", xmin = 1963, xmax = Inf, ymin = 25, ymax = 50,
           alpha = 0.2, fill = "palevioletred1")  
  annotate("rect", xmin = 1975, xmax = Inf, ymax = 25, ymin= 0,
           alpha = 0.2, fill = "palevioletred1")  
  scale_x_continuous(expand = c(0,0))  
  scale_fill_gradientn(colors = jet.colors(16), na.value = 'white')  
  theme_minimal()   
  theme(panel.grid = element_blank())  
  coord_cartesian(clip = 'off')  
  ggtitle(the_disease)  
  ylab("")  
  xlab("")    
  theme(legend.position = "bottom", text = element_text(size = 8))   
  annotate(geom = "text", x = 1963, y = 50.5, 
           label = "Vaccine introduced", size = 3, hjust = 0)

enter image description here

  • Related