交互式ggplot2热图

Interactive ggplot2 heat map

library(dplyr)

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)

我得到了上述格式的数据,并且我使用以下代码从中制作了一个 ggplot2 热图:

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()

有没有办法让它具有交互性?我知道我们使用 p 任意定义调用它然后我们可以使用

plotly::ggplotly(p)

但是我真的很困惑在这种情况下可以在哪里添加它以使其具有交互性。

我不完全清楚你在这里寻找什么,但我们可以使 ggplot 对象 "interactive",如你所说,使用 ggplotly;

library(dplyr)
library(ggplot2)
library(plotly)
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() %>%
  ggplotly(.)

或者您可以直接在 plotly 中制作热图;

Heat_clean %>% 
  mutate(color = case_when(Days <= 5 ~ 1, 
                           Days <= 15 ~ 2, 
                           Days <= 25 ~ 3, 
                           is.na(Days) ~ 4, 
                           TRUE ~ 5),
         color = as.factor(color)) %>% 
  plot_ly(z = .$color, 
          x = .$month, 
          y = .$Apartment_no, 
          type = "heatmap", showscale=FALSE, colorscale ="Viridis")