我想为
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)
)
创建于 2024-12-08,使用 reprex v2.1.1
如您所见,颜色并没有真正得到尊重并且相互混合。
有办法吗?
您可以通过将间隔的中点传递给
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)
)
)