Reputation: 735
I don't think this question has ever actually been answered on Stack Overflow (this answer provides a workaround, but that is all I could find, and the question is now over 10 years old).
I want to extract the color code information generated from the scale_fill_gradient(low = "skyblue", high = "dodgerblue4")
code used in the ggplot2
code shown below.
ggplot(mtcars, aes(wt*1000, mpg)) +
geom_point(size = 4, aes(colour = hp)) +
xlab("Weight (pounds)") + ylab("Miles per gallon (MPG)") + labs(color='Horse power') +
scale_x_continuous(limits = c(1000, 6000),
breaks = c(seq(1000,6000,1000)),
labels = c("1,000", "2,000", "3,000", "4,000", "5,000", "6,000")) +
scale_fill_gradient(low = "skyblue", high = "dodgerblue4") +
theme_classic()
Ideally, I would like to generate a dataset with a row for each point in the plot and columns with all the standard information (wt
, mpg
, hp
) but then also the color code of the individual points that can be seen on the plot. This would correspond with the hp
("Horse power") variable, as seen below, and would (presumably) be generated by the scale_fill_gradient
function. This would allow me to reproduce the color of a point on the plot with an hp
score of, say, 150.
Thanks in advance for any input.
Upvotes: 0
Views: 714
Reputation: 38003
You can extract any data, including colour codes, that the geom layer uses from the plot using layer_data()
:
library(ggplot2)
ggplot(mtcars, aes(wt*1000, mpg)) +
geom_point(size = 4, aes(colour = hp)) +
xlab("Weight (pounds)") + ylab("Miles per gallon (MPG)") + labs(color='Horse power') +
scale_x_continuous(limits = c(1000, 6000),
breaks = c(seq(1000,6000,1000)),
labels = c("1,000", "2,000", "3,000", "4,000", "5,000", "6,000")) +
scale_fill_gradient(low = "skyblue", high = "dodgerblue4") +
theme_classic()
ld <- layer_data(last_plot())
(head(ld))
#> colour x y PANEL group shape size fill alpha stroke
#> 1 #204464 2620 21.0 1 -1 19 4 NA NA 0.5
#> 2 #204464 2875 21.0 1 -1 19 4 NA NA 0.5
#> 3 #1C3C5A 2320 22.8 1 -1 19 4 NA NA 0.5
#> 4 #204464 3215 21.4 1 -1 19 4 NA NA 0.5
#> 5 #2E618C 3440 18.7 1 -1 19 4 NA NA 0.5
#> 6 #1E4261 3460 18.1 1 -1 19 4 NA NA 0.5
Created on 2021-07-13 by the reprex package (v1.0.0)
Upvotes: 1