ggplot2: get color palette used in scale_color

Asked

Viewed 73 times

3

Do you know if it is possible to get the color palette used in scale_color_*? I would like to get the specific colors (Hex color codes) used with the package paletteer in each case to then use it in other applications (for example, Join that data with others). What I tried was the following:

library(ggplot2)
library(dplyr)
library(paletteer)

dados <- data.frame(x = sample(seq(0,100), 100, replace = T),
                    y = sample(seq(0,10), 100, replace = T),
                    valor = sample(seq(-10,10), 100, replace = T))

plot.1 <- dados %>% 
  ggplot(aes(x = x, y = y, color = valor))+
  geom_point()+
  paletteer::scale_color_paletteer_c("ggthemes::Classic Red-White-Green") +
  theme_minimal()

After creating object Plot.1, I tried to check if ggplot2 saved colors in the data with plot.1$data, but that doesn’t happen. Then I tried to check on mapping with plot.1$mapping$colour, which returns the following result:

<quosure>
expr: ^cor
env:  000002299B6E1FD0

I don’t know if it’s possible to extract the Hex codes from there. At the end, I would like to have a set with the columns x, y, value and Hex, the latter obtained with the colors of the graphic generated above.

From now on, thank you to those who can help.

1 answer

3


From what I found you can use ggplot_build to assemble the chart information and extract the color from the data. Another option is to use paletteer functions to achieve colors.

library(ggplot2)
library(dplyr)
library(paletteer)

dados <- data.frame(x = sample(seq(0,100), 100, replace = T),
                    y = sample(seq(0,10), 100, replace = T),
                    valor = sample(seq(-10,10), 100, replace = T))

plot.1 <- dados %>% 
  ggplot(aes(x = x, y = y, color = valor))+
  geom_point()+
  paletteer::scale_color_paletteer_c("ggthemes::Classic Red-White-Green") +
  theme_minimal()


plot_build <- ggplot_build(plot.1)

unique(plot_build$data[[1]]$colour)
#>  [1] "#A81526" "#FFFEFE" "#CC312B" "#FFD9D1" "#5C9F5D" "#DB4E3E" "#C02829"
#>  [8] "#428F49" "#FCB4A5" "#B41F27" "#1B6D32" "#F48F7B" "#E86853" "#97C394"
#> [15] "#9C0824" "#74AF72" "#B9D7B7" "#DCEBDA" "#297839" "#09622A" "#368341"

paletteer::paletteer_c("ggthemes::Classic Red-White-Green", 21)
#> <colors>
#> #9C0824FF #A81526FF #B41F27FF #C02829FF #CC312BFF #DA4E3FFF #E86753FF #F48E7BFF #FCB4A5FF #FFD9D1FF #FFFFFFFF #DCEBDBFF #B9D7B7FF #97C394FF #74AF72FF #5C9F5DFF #428F49FF #368341FF #297839FF #1B6D31FF #09622AFF

Created on 2021-03-08 by the reprex package (v1.0.0)

  • perfect, Jorge, the function 'ggplot_build()' was exactly what I was looking for and did not find. Super worth!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.