[英]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)
我使用 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()+
geom_text(aes(x=month,y=Apartment_no,label=Days))-> p
plotly::ggplotly(p)
不幸的是,我用颜色代替了图例,我想要条件和颜色作为图例。 例如。 如果在上面的代码中看到当 Days<=5, color=Blue, 525, color=Green。 我希望他们成为传奇。 我现在的剧情可以看附图
处理此问题的最简单方法是映射要在图例中显示的类别名称,并将其用于美学映射以填充。 然后,您可以使用scale_fill_manual
提供您喜欢的颜色,ggplot 将提供类别标签。
## 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"
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.