我想正确设置scale_*_gradientn以使用特定的颜色图和颜色中断。 我发现如果不使用
limits =
就无法使其工作,但是,这会限制任何超出限制的值。
我知道我的色标中颜色之间的间隔并不均匀(由于物理原因),但是它们是对称的。
我明白
scale_*_gradientn
可能不是我应该使用的。
这是一个最小的例子:
library(tidyverse)
# Inputs
colorscale <- c("#760005", "#ec0013", "#ffa938", "#fdd28a", "#fefe53", "#ffffff", "#a2fd6e", "#00b44a", "#008180", "#2a23eb", "#a21fec")
breaks <- c(-2.00, -1.50, -1.20, -0.70, -0.50, 0.00, 0.50, 0.70, 1.20, 1.50, 2.00)
df <- data.frame(
year = seq(2000:2020),
value = c(0.24, 1.74, -2.33, 1.48, 0.38, 0.64, 0.97, -1.83, -1.25, -0.49, 3.15, -0.16, -0.12, 0.09, -1.67, -0.64, 0.39, 0.52, -0.58, 0.74, -1.24)
)
# Plot the data
ggplot(data = df, aes(x = year, y = value, fill = value)) +
theme_minimal() +
geom_bar(stat = "identity", color = "#c5c5c5c5", linewidth = 0.25) +
scale_fill_gradientn(colors = colorscale,
values = scales::rescale(breaks),
na.value = "#e5e5e5")
我可以使用
limits
参数强制它,但这会减少极值(我最感兴趣的):
ggplot(data = df, aes(x = year, y = value, fill = value)) +
theme_minimal() +
geom_bar(stat = "identity", color = "#c5c5c5c5", linewidth = 0.25) +
scale_fill_gradientn(colors = colorscale,
values = scales::rescale(breaks),
limits = c(-2,2),
na.value = "#e5e5e5")
谢谢!
您可以通过值范围的绝对最大值来计算零中心的限制。然后将最小值乘以 -1,将最大值乘以 +1,以获得与 0 相同的范围,如下所示:
library(tidyverse)
center_limits <- max(abs(df$value))*c(-1, 1)
# Plot the data
ggplot(data = df, aes(x = year, y = value, fill = value)) +
theme_minimal() +
geom_bar(stat = "identity", color = "#c5c5c5c5", linewidth = 0.25) +
scale_fill_gradientn(colors = colorscale,
values = scales::rescale(breaks),
na.value = "#e5e5e5",
limits = center_limits)
创建于 2024-04-03,使用 reprex v2.0.2