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时在上面的代码中看到。我希望他们成为传奇。我现在的情节可以在附图中看到
答案 0 :(得分:1)
处理此问题的最简单方法是映射要在图例中显示的类别名称,并使用该名称进行美感填充。然后,您可以使用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"
)