修剪ggplot中的scale_color_gradient()图例。

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

我正试图 "修剪 "下面的图例。

df <- data.frame(x = seq(0, 15 , 0.001), 
                 y = seq(0, 15, 0.001))

ggplot(df, aes(x=x, y=y, col = y)) +
  geom_line() +
  scale_color_gradientn(colours = c("green", "black", "red", "red"), 
                        values = rescale(x = c(0, 2, 4, 15), to = c(0,1), from = c(0, 15) ))

enter image description here

我可以设置所需的分界线和值,通过添加... ... breaks = c(0,2,4), labels = c("0", "2", "4+"):

enter image description here

但当我添加 limits=c(0,4)梯度变得混乱。

疑问

是否可以 "修剪 "图例,使其显示从0到4+的数值(即省略上面的所有数值)?

r ggplot2
1个回答
1
投票

以下是你可能想要的。

library(ggplot2)
library(scales)

df <- data.frame(x = seq(0, 15 , 0.001), 
                 y = seq(0, 15, 0.001))

ggplot(df, aes(x=x, y=y, col = y)) +
  geom_line() +
  scale_color_gradientn(colours = c("green", "black", "red", "red"), 
                        values = rescale(x = c(0, 2, 4, 15), from = c(0, 4)),
                        oob = squish,
                        limits = c(0, 4))

事情的经过如下。假设我们在数据空间中有一些值(意味着它们还没有被重新缩放)。

# Colour positions in data space
print(col_pos_data <- c(0, 2, 4, 15))
#> [1]  0  2  4 15

默认情况下, scales::rescale() 函数将所有的值都纳入 [0,1] 区间。然而,当你设置一个自定义范围时,任何越界值将与界内值线性缩放。你会发现,在这种情况下,15变成了3.75。

# Colour positions in [0,1] interval
col_pos_scaled <- rescale(col_pos_data, from = c(0, 4))
print(col_pos_scaled)
#> [1] 0.00 0.50 1.00 3.75

然而,ggplot强制执行连续比例限制的默认方式是将任何超出限制的值设置为 NA往往会在之后被删除。

# Default ggplot limit enforcing
print(censor(col_pos_scaled))
#> [1] 0.0 0.5 1.0  NA

现在,这对你的比例尺来说有点太糟糕了,但其中一个选择是 "压缩 "数据。这将任何(有限的)超出边界的值带到最近的极限。NA 但设置为[0,1]区间的最大限制。

print(scaled_squish <- squish(col_pos_scaled))
#> [1] 0.0 0.5 1.0 1.0

如果对范围进行相应调整,对于数据空间中的值也是一样的。

print(censor(col_pos_data, range = c(0, 4)))
#> [1]  0  2  4 NA

print(data_squish <- squish(col_pos_data, range = c(0, 4)))
#> [1] 0 2 4 4

在内部,ggplot 会将所有数据重新缩放到极限,对于 squishingrescaling 来说,操作的顺序并不重要,所以数据值和 [0,1] 中的颜色位置会很好地对齐。

# So when data values are rescaled, they match up the colours
identical(rescale(data_squish), scaled_squish)
#> [1] TRUE

创建于2020-04-24,由 重读包 (v0.3.0)

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