Reputation: 2005
I was looking for a way to dplyr::mutate()
a new column based on a color gradient scale. To illustrate, see the following graph:
library(ggplot2)
ggplot(mtcars, aes(mpg, hp, color = hp)) +
geom_point() +
scale_color_gradient(low = "red", high = "blue")
Created on 2021-02-08 by the reprex package (v1.0.0)
My goal is to find a function that would map the hp
column, and depending on its value, retrieve the hex code. I would like to get all the codes that were used in scale_color_gradient()
in a column. For example:
#> # 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
Of course, the #000000
is just an example, I would like to retrieve the codes from the colors used in the graph.
Upvotes: 0
Views: 991
Reputation: 37933
You can use the functions in the scales package to do the same thing as ggplot2 does.
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()
Proof the colours are the same
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
Upvotes: 3
Reputation: 2485
Try this:
p <- ggplot(mtcars, aes(mpg, hp, color = hp)) +
geom_point() +
scale_color_gradient(low = "red", high = "blue")
build_p <- ggplot_build(p)
build_p$data[[1]]$colour
Upvotes: 1