ggplot图例-如何更改颜色扩散?

时间:2019-02-10 02:13:35

标签: r ggplot2 legend raster

我想更改图例栏的展开显示,如下所示。在示例1中,我想在图例栏的中间显示“ 100”阈值。在示例2中,我想在图例栏的中间显示平均值(白色)。我怀疑两者都需要类似的代码行。有人可以帮我这个忙吗?

#library
library(raster)
library(ggplot2)

#sample raster
r <- raster(ncol=36, nrow=18)
r[] <- (-ncell(r)/2+1):(ncell(r)/2)
r[1,] <- 5000
plot(r)

var_df <- as.data.frame(rasterToPoints(r))

### example 1
p <- ggplot() 
p <- p + geom_raster(data = var_df , aes(x = x, y = y, fill = layer))
p <- p + coord_equal()
p <- p + scale_fill_gradientn(
  colours=c("red", "yellow", "skyblue", "darkblue"),
  values = rescale(c(min(var_df$layer),
                     100,
                     100.01,
                     max(var_df$layer))))
p
### example 2
meanval <- mean(var_df$layer)
p <- ggplot() 
p <- p + geom_raster(data = var_df , aes(x = x, y = y, fill = layer))
p <- p + coord_equal()

p <- p + scale_fill_gradient2(low = muted("red"), mid = "white",
                              high = muted("blue"), midpoint = meanval)
p

enter image description here

0 个答案:

没有答案