在 `scale_fill_stepsn()` 中指定不对称中断

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

我想为

fill
美学添加阶梯渐变,并为特定间隔添加特定颜色。

例如,我想要 0 到 15 之间的红色,15 到 18 之间的蓝色,等等。

这是我(痛苦地)最接近我的目标:

library(tidyverse)
val_breaks = c(0, 15, 18, 20, 25)
col_breaks = c("red", "blue", "yellow", "purple")

#4 intervals, 4 colors
cut(mtcars$qsec, breaks=val_breaks) %>% levels()
#> [1] "(0,15]"  "(15,18]" "(18,20]" "(20,25]"

mtcars %>%
  ggplot(aes(x = mpg, y = wt, color = qsec)) +
  geom_point(size = 3) +
  scale_color_stepsn(
    colors=col_breaks,
    limits=c(0,25),
    breaks=val_breaks,
    values=scales::rescale(val_breaks)
  )

ggplot output

创建于 2024-12-08,使用 reprex v2.1.1

如您所见,颜色并没有真正得到尊重并且相互混合。

有办法吗?

r ggplot2 scale
1个回答
0
投票

您可以通过将间隔的中点传递给

values=
参数并根据用于比例的
from=
设置
rescale
limits=
参数来实现所需的结果:

library(tidyverse)

val_breaks <- c(0, 15, 18, 20, 25)
col_breaks <- c("red", "blue", "yellow", "purple")

mtcars %>%
  ggplot(aes(x = mpg, y = wt, color = qsec)) +
  geom_point(size = 3) +
  scale_color_stepsn(
    colors = col_breaks,
    limits = c(0, 25),
    breaks = val_breaks,
    values = scales::rescale(
      (val_breaks[-length(val_breaks)] + val_breaks[-1]) / 2,
      from = c(0, 25)
    )
  )

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