交互式ggplot2热图

时间:2019-11-21 17:02:34

标签: r ggplot2 dplyr plotly r-plotly

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)

我获得了以上格式的数据,并使用以下代码制作了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)

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

1 个答案:

答案 0 :(得分:0)

library(dplyr)
library(ggplot2)
library(plotly)

我尚不清楚您要在这里找到什么,但是我们可以使用ggplot使ggplotly对象“ interactive” 成为您所说的:

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

ggplotly(p)

或者您可以直接在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")