Home > database >  Ggplot center color scale at zero in scale_fill_stepsn
Ggplot center color scale at zero in scale_fill_stepsn

Time:11-22

Working data

m=raster(ncol=10,nrow=10)
m[,]=runif(100, -0.8, 0.5)
tmp=data.table(as.data.frame(m,xy=TRUE))
ggplot()  geom_tile(data = tmp, aes(x = x, y = y ,fill=layer))  
scale_fill_stepsn(colors=c('#b2182b','#ef8a62','#fddbc7','#f7f7f7','#d1e5f0','#67a9cf','#2166ac'),n.breaks=10)

However this doesn't center at zero as some negative values are blue enter image description here

I am trying to plot multiple figures that show data somewhere between -1 and 1, however most of the figures' data are not centered around zero because the positive or negative data have a larger range. In the plot I would like positive values to be shown in blue and positive values in red and to control the binnes to be 0.1 or 0.2 apart.

How do I programmatically force the color scale in scale_fill_stepsn to be centered at zero without fiddling all the time with breaks? I have tried to play with n.breaks and tried scale_fill_steps2 with which I don't have much control on the color scale.

CodePudding user response:

In my opinion a symmetric scale centered around zero could be a good solution.

library(raster)
library(data.table)
library(ggplot2)

set.seed(12345)
m <- raster(ncol=10,nrow=10)
m[,] <- runif(100, -0.8, 0.5)
tmp <- data.table(as.data.frame(m,xy=TRUE))
lmt <- ceiling(10*max(abs(range(tmp$layer))))/10

ggplot()  
  geom_tile(data = tmp, aes(x = x, y = y ,fill=layer))  
  scale_fill_stepsn(colors=c('#b2182b','#ef8a62','#fddbc7',
                             '#f7f7f7','#d1e5f0','#67a9cf','#2166ac'),
             n.breaks=10, limits=c(-lmt,lmt), show.limits=T)

enter image description here

  • Related