Say I create a plot:
df <- data.frame(A = 1:100, B = jitter(1:100, 25), C = c('One', 'Two'))
p <- ggplot(df, aes(A, B, colour = C)) +
geom_point() +
scale_colour_manual(values = c('red', 'green'))
Where are those colours (red and green) stored in p
?
I can see the palette of functions being used in a function here:
p$scales$scales[[1]]$palette
The contents of this function are:
function (n)
{
if (n > length(values)) {
stop("Insufficient values in manual scale. ", n, " needed but only ",
length(values), " provided.", call. = FALSE)
}
values
}
I think the colours must be stored in values
there but I have no idea where they actually are in p
.
P.s. I've seen this question: How to extract the fill colours from a ggplot object?. But for what I'm trying to do I can't build the plot. I need to get at the colours before it's built.
If there was some way of recursively searching p
for the characters "red" or "green" that would probably help find these values.
EDIT: What I'm ultimately trying to do.
I'm trying to edit plots before they are plotted. The idea being that given some plot p
you can just do something like this:
apply_theme(p)
...and a colour scheme is applied to the entire plot (including scales, gradients etc.). This is to avoid having to do things like:
p + some_theme + scales_colour_manual(values = plot_theme)
I'm trying to reduce effort by the user so that they can just apply a theme to an entire plot and not have to worry about whether they are colouring a gradient, discrete scale or whatever.
Building the plot is a partial solution. But I would like to able to apply the theme and still be able to edit the plot later.
I've been able to edit p
so that whatever colours are applied to geoms retrospectively. But I just can't find how to do that with scale colours. I know the colours must be in there somewhere!