@baptiste pointed me to a message board post that mentions the function set_default_scale
which can be used to set a default palette. The following solution only works with old versions of ggplot2, though.
First we need a function that produces colour names or codes. I called mine magazine.colours
:
magazine.colours <- function(n, set=NULL) {
set <- match.arg(set, c('1', '2'))
palette <- c("red4", "darkslategray3", "dodgerblue1", "darkcyan",
"gray79", "black", "skyblue2", "dodgerblue4",
"purple4", "maroon", "chocolate1", "bisque3", "bisque",
"seagreen4", "lightgreen", "skyblue4", "mediumpurple3",
"palevioletred1", "lightsalmon4", "darkgoldenrod1")
if (set == 2)
palette <- rev(palette)
if (n > length(palette))
warning('generated palette has duplicated colours')
rep(palette, length.out=n)
}
(It accepts an optional set
argument just to show that you are not restricted to a single palette.) Ok, now we create a "scale", which I called magazine
. It's based on ggplot's brewer scale and the code is pretty ugly:
ScaleMagazine <- proto(ScaleColour, expr={
objname <- 'magazine'
new <- function(., name=NULL, set=NULL, na.colour='yellowgreen',
limits=NULL, breaks = NULL, labels=NULL,
formatter = identity, variable, legend = TRUE) {
b_and_l <- check_breaks_and_labels(breaks, labels)
.$proto(name=name, set=set, .input=variable, .output=variable,
.labels = b_and_l$labels, breaks = b_and_l$breaks,
limits= limits, formatter = formatter, legend = legend,
na.colour = na.colour)
}
output_set <- function(.) {
missing <- is.na(.$input_set())
n <- sum(!missing)
palette <- magazine.colours(n, .$set)
missing_colour(palette, missing, .$na.colour)
}
max_levels <- function(.) Inf
})
scale_colour_magazine <- ScaleMagazine$build_accessor(list(variable = '"colour"'))
scale_fill_magazine <- ScaleMagazine$build_accessor(list(variable = '"fill"'))
The important thing here is to define output_set
which is the function that ggplot calls to get the colour names/codes. Also, if you need extra arguments, those must be included in new
and later can be accessed as .$argument_name
. In the example above, output_set
simply calls magazine.colours
.
Now, check the new scale does actually work:
qplot(mpg, wt, data=mtcars, shape=21,
colour=factor(carb), fill=factor(carb)) +
scale_colour_magazine(set='1') +
scale_fill_magazine(set='1')
To make it the default, simply use set_default_scale
.
set_default_scale("colour", "discrete", "magazine")
set_default_scale("fill", "discrete", "magazine")
And that'll be it.
> qplot(mpg, wt, data=mtcars, colour=factor(carb), fill=factor(carb))