我使用 ggplot2 生成了以下图表。我想了解如何根据以下颜色十六进制代码和值规范有条件地格式化每个图 block 的颜色
#0a5d00 if Value > 2
#0eff00 if Value > 1 and < 2
#ece75f if Value > 0 and < 1
#e6cc00 if Value > -1 and < 0
#ff0000 if Value > -2 and < -1
#7b0000 if Value < -2
data <- structure(list(Date = structure(c(18993, 19024, 19052, 19083,
19113, 19144, 19174, 19205, 19236, 19266), class = "Date"), Value = c(-3,
-2, -1.5, -1, -0.5, 0, 0.5, 1, 2, 3)), class = c("tbl_df", "tbl",
"data.frame"), row.names = c(NA, -10L))
library(tidyverse)
data %>%
ggplot(aes(Date, Value, fill = Value)) +
geom_tile()
最佳答案
感谢@Tanga94更新添加scale_identity()
:
library(tidyverse)
data %>%
mutate(my_color = case_when(
Value > 2 ~ "#0a5d00",
Value > 1 & Value < 2 ~ "#0eff00",
Value > 0 & Value< 1 ~ "#ece75f",
Value > -1 & Value < 0 ~ "#e6cc00",
Value > -2 & Value< -1 ~ "#ff0000",
Value < -2 ~ "#7b0000",
TRUE ~ NA_character_
)) %>%
ggplot(aes(Date, Value, fill = my_color)) +
geom_tile() +
scale_fill_identity()
关于r - ggplot2中平铺图的条件格式颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74503050/