r - ggplot2中平铺图的条件格式颜色

标签 r ggplot2

我使用 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()

enter image description here

关于r - ggplot2中平铺图的条件格式颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74503050/

相关文章:

r - 如何使用ggplot2创建一维图表?

r - 如何让我的图例点变成蓝色和红色,而不是两者都是红色?

r - 在 ggplot 中使用 facet_wrap 时缩放 y 轴

r - 使用 ggplot 标记异常值

r - 如何(更容易)在 ggplot2 中创建漂亮的 x 轴刻度(即 pi/2, pi, 3pi/2, ...)?

r - 如何加载 rjags

R:添加一个 dplyr 组标签作为数字

r - 为什么 ACF 不绘制滞后

r - 如何在 R 包中使用 'src/' 中的子文件夹?

r - 如何计算和测试总和并重复操作