r - geom_raster 具有基于特定离散值的颜色

标签 r dataframe ggplot2 classification geom-raster

我想根据特定分类绘制带有颜色的 geom_raster: enter image description here

我尝试了以下代码(变量 = SPI),但它不起作用:

scale_fill_gradient(colours = c( "brown","burlywood","bisque","aliceblue","cadetblue2","blue"), 
                      breaks=c(-2,-1.5,-1,1,1.5,2), labels = format(c("-2","-1.5","-1","1","1.5","2")))

示例:

year <- seq(1977,2021,1)
jan = runif(45, min=-4, max=4)
feb = runif(45, min=-4, max=4)
mar = runif(45, min=-4, max=4)
apr = runif(45, min=-4, max=4)
may = runif(45, min=-4, max=4)
jun = runif(45, min=-4, max=4)
jul = runif(45, min=-4, max=4)
aug = runif(45, min=-4, max=4)
sep = runif(45, min=-4, max=4)
oct = runif(45, min=-4, max=4)
nov = runif(45, min=-4, max=4)
dec = runif(45, min=-4, max=4)

df = data.frame(year,jan,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec)
df <- reshape2::melt(df, id.vars = "year")

df$year <- factor(df$year, levels = (unique(df$year)))
df$variable <- factor(df$variable, levels = (unique(df$variable)))

library(ggplot2)
e1 <- ggplot(df, aes(x = variable, y = year, fill = value)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_gradient(colours = c( "brown","burlywood","bisque","aliceblue","cadetblue2","blue"), 
                      breaks=c(-2,-1.5,-1,1,1.5,2), labels = format(c("-2","-1.5","-1","1","1.5","2")))+
  theme(legend.position="bottom")

e1

非常感谢和亲切的问候!

最佳答案

您可以指定一个列,将连续值分类为不同的类别,然后使用它来手动设置您想要的颜色。

df$col <- as.factor(findInterval(df$value, c(-2,-1.5,-1,1,1.5,2), all.inside = T))

ggplot(df, aes(x = variable, y = year, fill = col)) +
  geom_raster() +
  guides(fill=guide_legend(title="Bohicon:")) +
  scale_fill_manual(values  =c( "brown","burlywood","bisque","aliceblue","cadetblue2","blue"),
                    labels = format(c("-2","-1.5","-1","1","1.5","2"))) + 
  theme(legend.position="bottom")

情节:

enter image description here

关于r - geom_raster 具有基于特定离散值的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76382042/

相关文章:

python - 迭代列并在达到特定数字时返回列名称

python - 在不更改组顺序的情况下按第一个值对组进行排序

R dplyr : change the row value of columns having an specific name

r - R中绘图中同一组的循环点

r - 如何从 R 获取当前 git commit 的 sha

r - 更改多语言 knitr/RMarkdown 文档中的提示

r - 获取非 NA 列表元素的索引和值

r - 按组和列的加权均值

r - gganimate 根据时间对多条路径进行动画处理

r - 回归线的热图