首页 > 解决方案 > 在ggplot2中手动添加渐变色列

问题描述

我正在寻找一种dplyr::mutate()基于颜色渐变比例的新列的方法。为了说明,请参见下图:

library(ggplot2)

ggplot(mtcars, aes(mpg, hp, color = hp)) +
  geom_point() +
  scale_color_gradient(low = "red", high = "blue")

reprex 包于 2021-02-08 创建(v1.0.0)

我的目标是找到一个可以映射hp列的函数,并根据它的值检索十六进制代码。我想获取scale_color_gradient()列中使用的所有代码。例如:

#> # A tibble: 32 x 12
#>      mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb color  
#>    <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <chr>  
#>  1  21       6  160    110  3.9   2.62  16.5     0     1     4     4 #000000
#>  2  21       6  160    110  3.9   2.88  17.0     0     1     4     4 #000000
#>  3  22.8     4  108     93  3.85  2.32  18.6     1     1     4     1 #000000
#>  4  21.4     6  258    110  3.08  3.22  19.4     1     0     3     1 #000000
#>  5  18.7     8  360    175  3.15  3.44  17.0     0     0     3     2 #000000
#>  6  18.1     6  225    105  2.76  3.46  20.2     1     0     3     1 #000000
#>  7  14.3     8  360    245  3.21  3.57  15.8     0     0     3     4 #000000
#>  8  24.4     4  147.    62  3.69  3.19  20       1     0     4     2 #000000
#>  9  22.8     4  141.    95  3.92  3.15  22.9     1     0     4     2 #000000
#> 10  19.2     6  168.   123  3.92  3.44  18.3     1     0     4     4 #000000
#> # … with 22 more rows

当然,这#000000只是一个例子,我想从图中使用的颜色中检索代码。

标签: rggplot2

解决方案


您可以使用 scales 包中的函数来执行与 ggplot2 相同的操作。

library(ggplot2)
library(scales)
library(dplyr)

df <- mtcars %>% 
  mutate(colour = seq_gradient_pal("red", "blue")(rescale(hp)))

# Showing the colours
ggplot(df, aes(mpg, hp, colour = I(colour))) +
  geom_point()

证明颜色是一样的

g <- ggplot(mtcars, aes(mpg, hp, colour = hp)) +
  geom_point() +
  scale_colour_gradient(low = "red", high = "blue")
g <- layer_data(g)

all(g$colour == df$colour)
#> [1] TRUE

推荐阅读