@baptiste指向了一个帖子,其中提到了函数set_default_scale
,可以用于设置默认调色板。下面的解决方案只适用于旧版本的ggplot2。
首先,我们需要一个生成颜色名称或代码的函数。我称之为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)
}
(它接受一个可选的 set
参数,只是为了说明你并不局限于一个调色板。) 现在我们创建一个“比例尺”,我称之为magazine
。它基于ggplot的brewer比例尺,代码相当丑陋:
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"'))
重要的是要定义
output_set
函数,这是ggplot调用以获取颜色名称/代码的函数。而且,如果您需要额外的参数,则必须包含在
new
中,稍后可以作为
.$argument_name
访问。在上面的示例中,
output_set
仅调用
magazine.colours
。
现在,请检查新比例尺是否实际上有效:
qplot(mpg, wt, data=mtcars, shape=21,
colour=factor(carb), fill=factor(carb)) +
scale_colour_magazine(set='1') +
scale_fill_magazine(set='1')
要将其设置为默认值,只需使用
set_default_scale
。
set_default_scale("colour", "discrete", "magazine")
set_default_scale("fill", "discrete", "magazine")
就这样了。
> qplot(mpg, wt, data=mtcars, colour=factor(carb), fill=factor(carb))
![显示新调色板的图表](https://istack.dev59.com/LiB9t.webp)