我尝试了以下代码(变量 = 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")
情节:
关于r - geom_raster 具有基于特定离散值的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76382042/