Kartik Kaushal
Kartik Kaushal

Reputation: 35

How to put legends on interactive ggplot2 heat map

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
Apartment_no <- c("1-SV","1-SV","1-SV","1-SH","1-SH","1-SH","1-1V","1-1V","1-1V","1-1H","1-1H","1-1H","3-SV","3-SV","3-SV","3-1V","3-1V","3-1V","3-1H","3-1H","3-1H")
month <- c("September","October","November","September","October","November","September","October","November","September","October","November","September","October","November","September","October","November","September","October","November")
Days <- c(19,19,28,2,19,28,2,19,28,2,19,28,25,31,28,12,29,24,8,26,19)
Heat_clean <- data.frame(Apartment_no,month,Days)

I have created an interactive heat map using ggplot2. I used the following code:

Heat_clean %>% 
mutate(color = case_when(Days <= 5 ~ "blue", 
Days <= 15 ~ "orange", 
Days <= 25 ~ "pink", 
is.na(Days) ~ "red", TRUE ~ "green")) %>% 
ggplot(aes(month,Apartment_no)) + 
geom_tile(aes(fill=color),color="white")+
scale_fill_identity()+
geom_text(aes(x=month,y=Apartment_no,label=Days))-> p

plotly::ggplotly(p)

Unfortunately, I am getting colors in the place of legends & I want the conditions along with the colors as legends. For eg. if seen in the above code when Days<=5, color=Blue, 525, color=Green. I would like them as legends. My present plot can be seen in the attached figure Current figure

Upvotes: 1

Views: 206

Answers (1)

Brian Fisher
Brian Fisher

Reputation: 1367

The simplest way to handle this is to map the category names you want to show up in the legend and use that for the aesthetic mapped to fill. You can then provide the colors you like with scale_fill_manual and ggplot will supply the category labels.

## separating assignment and plotting into separate blocks, to allow more control
clean_heat <- Heat_clean %>% 
      mutate(color = case_when(Days <= 5 ~ "Less than 5", 
                               Days <= 15 ~ "5 to 15", 
                               Days <= 25 ~ "15 to 25", 
                               is.na(Days) ~ "missing", TRUE ~ "more than 25"))

# Using factors to allow for control about plotting order. The following makes it an ordered factor

clean_heat$color <- factor(clean_heat$color, 
                           levels = c( "Less than 5",    "5 to 15",  "15 to 25"  ,    "more than 25", "missing")
)

clean_heat %>%
      ggplot(aes(month,Apartment_no, fill = color)) + 
      geom_tile(color = "white")+
      geom_text(aes(x=month,y=Apartment_no,label=Days))+
      scale_fill_manual(
            values = c("blue", "orange", "pink", "green", "red"),
            name = "Legend"
            )

enter image description here

Upvotes: 1

Related Questions