Is it possible to extract color information and values from scale_color_gradientn()?

46 views
Skip to first unread message

Kristoffer Magnusson

unread,
Sep 14, 2012, 3:49:37 AM9/14/12
to ggp...@googlegroups.com
Hi,

I'm interested in extracting the color values that's used in scale_color_gradientn(), for instance take this example code:

library(ggplot2)

z <- rgamma(1000, shape=0.2, scale=10000)
hist(z)
x <- data.frame("x" = runif(1000), y=runif(1000), z=z)

my_cols <- c("#fef29f", "#fee47c", "#fed158", "#feb934", "#fe8b29", "#fe581e", "#ef2c19", "#df1424", "#cb0f39", "#b60b4b", "#a10757", "#8d045f", "#780262", "#640060")
my_vals <- c(0.1, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000)

ggplot(aes(x = x, y = y, fill=z, color=z), data = x) + 
  geom_point(size=3) + 
  scale_color_gradientn(colours=my_cols, values=my_vals, na.value="#f9fff1", rescaler = function(x, ...) x, oob = identity)
 
Here, I'm interested in extracting color values for each value in z. Basically I want to create a color legend for all values in z. I is possible to extract this from ggplot?

Thanks!

/Kristoffer Magnusson

Kristoffer Magnusson

unread,
Sep 14, 2012, 7:16:34 AM9/14/12
to ggp...@googlegroups.com
Here's a more clear example. What's the color value for say z = 4000, or z = 2569 etc. 

library(ggplot2)

z <- rgamma(10000, shape=0.2, scale=10000)
x <- data.frame("x" = seq(1,10000), y=rep(1,length.out=10000), z=z)

x$z <- sort(x$z)

my_cols <- c("#fef29f", "#fee47c", "#fed158", "#feb934", "#fe8b29", "#fe581e", "#ef2c19", "#df1424", "#cb0f39", "#b60b4b", "#a10757", "#8d045f", "#780262", "#640060")
my_vals <- c(0, 5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000)

ggplot(aes(x = x, y = y, color=z), data = x) + 
  geom_tile(size=3) + 
Reply all
Reply to author
Forward
0 new messages