[英]define color gradient for negative and positive values scale_fill_gradientn()
[英]Raster map with discrete color scale for negative and positive values R
我有兩個我想要映射的數據幀。 在DFS有相同的xy坐標我需要一個可見的離散色標 單彩條像這里顯示的兩個DFS。 我希望colorkey中的顏色與自定義的斷點相匹配。 可以在此示例之外應用的更通用的解決方案非常受歡迎
來自RcolorBrewer包的RdYIBu調色板就是我追求的。
我的代碼到目前為止:
library(rasterVis)
ras1 <- raster(nrow=10,ncol=10)
set.seed(1)
ras1[] <- rchisq(df=10,n=10*10)
ras2=ras1*(-1)/2
s <- stack(ras1,ras2)
Uniques <- cellStats(s,stat=unique)
Uniques.max <- max(Uniques)
Uniques.min <- min(Uniques)
my.at <- round(seq(ceiling(Uniques.max), floor(Uniques.min), length.out= 10),0)
myColorkey <- list(at=my.at, labels=list(at=my.at))
levelplot(s, at=my.at, colorkey=myColorkey,par.settings=RdBuTheme())
如何設置colorkey中的值以匹配地圖上的值,如上面的示例地圖所示? 請注意,colorkey中的顏色數應與地圖上顯示的數字相同。
非常感謝您的幫助。 您的建議將幫助我開發許多這樣的地圖。
謝謝。
以下內容應該讓你去。 使用ggplot2文檔和許多在線示例,您應該能夠調整美學,使其看起來完全符合您的要求,沒有任何麻煩。歡呼。
#Order breaks from lowest to highest
my_at <- sort(my_at)
#Get desired core colours from brewer
cols0 <- brewer.pal(n=length(my_at), name="RdYlBu")
#Derive desired break/legend colours from gradient of selected brewer palette
cols1 <- colorRampPalette(cols0, space="rgb")(length(my_at))
#Convert raster to dataframe
df <- as.data.frame(s, xy=T)
names(df) <- c("x", "y", "Epoch1", "Epoch2")
#Melt n-band raster to long format
dfm <- melt(df, id.vars=c("x", "y"), variable.name="epoch", value.name="value")
#Construct continuous raster plot without legend
#Note usage of argument `values` in `scale_fill_gradientn` -
#-since your legend breaks are not equi-spaced!!!
#Also note usage of coord_equal()
a <- ggplot(data=dfm, aes(x=x, y=y)) + geom_raster(aes(fill=value)) + coord_equal()+
facet_wrap(facets=~epoch, ncol=1) + theme_bw() +
scale_x_continuous(expand=c(0,0))+
scale_y_continuous(expand=c(0,0))+
scale_fill_gradientn(colours=cols1,
values=rescale(my_at),
limits=range(dfm$value),
breaks=my_at) +
theme(legend.position="none", panel.grid=element_blank())
#Make dummy plot discrete legend whose colour breaks go along `cols1`
df_leg <- data.frame(x=1:length(my_at), y=length(my_at):1, value=my_at)
gg_leg <- ggplot(data=df_leg, aes(x=x, y=y)) + geom_raster(aes(fill=factor(value))) +
scale_fill_manual(breaks=my_at, values=cols1,
guide=guide_legend(title="",
label.position="bottom")) +
theme(legend.position="bottom")
#Extract discrete legend from dummy plot
tmp <- ggplot_gtable(ggplot_build(gg_leg))
leg <- which(sapply(tmp$grobs, function(x) x$name)=="guide-box")
legend <- tmp$grobs[[leg]]
#Combine continuous plot of your rasters with the discrete legend
grid.arrange(a, legend, ncol=1, heights=c(4, 0.8))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.