geom_raster颜色基于特定离散值

bkhjykvo  于 2023-06-03  发布在  其他
关注(0)|答案(2)|浏览(209)

我想绘制一个geom_raster,颜色基于特定的分类:

我尝试了下面的代码(变量= 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

非常感谢和亲切的问候!

wsxa1bj1

wsxa1bj11#

您可以指定一个列,将连续值分类到不同的类中,然后使用该列手动设置所需的颜色。

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")

Plot:

oxosxuxt

oxosxuxt2#

我可能错过了一些东西,但我认为你可能需要另一个休息,以获得表中所示的削减。我还在这个帐户的情节中添加了另一种颜色。我没有检查切口和标签是否匹配。

df$val_cut <- cut(df$value, breaks = c(-Inf, -2, -1.5, -1, 1, 1.5, 2, Inf), 
                  labels = c("<= -2", "-1.99 to -1.5", "-1.49 to -1", " -0.99 to 0.99", "1 to 1.49", "1.5 to 1.99", ">=2"))

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.3
ggplot(df, aes(x = variable, y = year, fill = val_cut)) +
  geom_raster()+
  guides(fill=guide_legend(title="Bohicon"))+
  scale_fill_manual(values = c( "brown","burlywood","bisque","aliceblue","cadetblue2","blue", "black"))

<sup>Created on 2023-06-01 with [reprex v2.0.2](https://reprex.tidyverse.org)</sup>

相关问题