如何在ggplot2中自定义连续数据离散化的颜色对应关系

问题描述 投票:0回答:1

数据:

library(terra)
library(legendry)
library(tidyverse)
library(tidyterra)

m <- matrix(c(1:24,25), nrow=5, ncol=5) 
n <- matrix(rep(5,time=25),nrow = 5,ncol = 5)

## as.double() ----
dt <- rast(c(A = rast(m),B = rast(n))) |> 
  as.double() 

获得的颜色应该进行插值。但最高/最低值并不严格对应红/蓝。

ggplot() +
  geom_spatraster(data = rast(m), na.rm = TRUE) +
  scale_fill_steps2(
    low = 'blue',
    mid = 'white',
    high = 'red',
    midpoint = 10,
    na.value = NA, 
    guide = guide_colourbar(
      barwidth = unit(5, "cm"),  
      barheight = unit(0.4, "cm"), 
      title = 'Pre (mm/day)',
      title.position = "top",
      position = 'bottom'
    )
  ) +
  scale_y_continuous(expand = c(0, 0)) + 
  scale_x_continuous(expand = c(0, 0)) +
  theme_bw() +
  theme(aspect.ratio = 1)

enter image description here

尝试为不同的区间制作自定义颜色,结果并不是严格对应的结果。

ggplot() +
  geom_spatraster(data = dt, na.rm = TRUE) +
  scale_fill_stepsn(
    # n.breaks = 5,
    colors = c("blue", 'green', "yellow", "orange", "red"), 
    breaks = c (5, 10, 15, 20), 
    na.value = NA, 
    guide = guide_colourbar(
      barwidth = unit(5, "cm"), 
      barheight = unit(0.4, "cm"), 
      title = 'Pre (mm/day)',
      title.position = "top",
      position = 'bottom'
    )
  ) +
  facet_grid(~lyr) +
  scale_y_continuous(expand = c(0, 0)) + 
  scale_x_continuous(expand = c(0, 0)) +
  theme_bw() +
  theme(aspect.ratio = 1)

enter image description here

我在https://ggplot2-book.org/scales-colour#sec-binned-colour中没有得到非常明确的答案。这是什么原因呢?有什么好的办法可以解决吗

r ggplot2
1个回答
0
投票

假设您有 1 到 25 之间的正确中点(是 13,而不是 11)。垃圾箱的颜色方式为:1 为纯蓝色,13 为纯白色,25 为纯红色。但垃圾箱的颜色是根据每个垃圾箱的“中心”所在的位置而定的。这意味着第一个 bin 不是纯蓝色,而是相当于“3”将着色的颜色的值(纯蓝色和白色之间的六分之一)。顶部 bin 的颜色与 22.5 对应的值类似(白色和红色之间的 19/24) 如果您希望末端垃圾箱为纯蓝色和纯红色,则需要使用

scale_fill_stepsn

 在每个垃圾箱的任一端指定纯红色和纯蓝色
ggplot() + geom_spatraster(data = dt, na.rm = TRUE) + scale_fill_stepsn( colors = c('blue', "blue", "white", "red", "red"), values = (c(1, 5, 13, 20 + 1e-6, 25) - 1)/24, breaks = c(0, 5, 10, 15, 20, 25), limits = c(0, 25), na.value = NA, guide = guide_colourbar( barwidth = unit(5, "cm"), barheight = unit(0.4, "cm"), title = 'Pre (mm/day)', title.position = "top", position = 'bottom' ) ) + scale_y_continuous(expand = c(0, 0)) + scale_x_continuous(expand = c(0, 0)) + facet_wrap(~lyr) + theme_bw() + theme(aspect.ratio = 1)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.