如果我正确理解你的问题,你想创建一个自定义scale_...
功能。简而言之,这是对源代码的深入研究。
我将展示一种方法,该方法只需修改包 RColorBrewer、scales,当然还有 ggplot2 中的现有函数。
- 核心是修改
RcolorBrewer::brewer.pal
,我想这基本上就是你想要的。看到代码,它会根据您的“n”从颜色列表中选择正确的颜色。这就是你需要手动创建的。我刚刚复制了调色板“YlOrBr”中的颜色。需要考虑的事情:Brewer 调色板不是随机的,它们已经过测试和创建,可以识别打印、复印和色盲,所以我不确定创建自己的调色板是否非常聪明。看一下https://colorbrewer2.org/找到合适的调色板。
- 修改底层颜色选择器
scales:::brewer_pal
- 修改
scale_fill/scale_color
功能
我已将功能归结为核心,因此它们不会进行通常的检查,并且灵活性较差。您可以修改原始功能以恢复此功能。
library(ggplot2)
mybrewerpal <- function(n, name) {# modified RcolorBrewer::brewer.pal
## the first call to switch would not be necessary in this example,
## but I leave it in order to make the underlying structure in brewer.pal clearer
switch(name, mypal = switch(n - 2, rgb(c(255, 254, 217), c(247, 196, 95), c(188, 79, 14), maxColorValue = 255),
rgb(c(255, 254, 254, 204), c(255, 217, 153, 76), c(212, 142, 41, 2), maxColorValue = 255),
rgb(c(255, 254, 254, 217, 153), c(255, 217, 153, 95, 52), c(212, 142, 41, 14, 4), maxColorValue = 255),
rgb(c(255, 254, 254, 254, 217, 153), c(255, 227, 196, 153, 95, 52), c(212, 145, 79, 41, 14, 4), maxColorValue = 255),
rgb(c(255, 254, 254, 254, 236, 204, 140), c(255, 227, 196, 153, 112, 76, 45), c(212, 145, 79, 41, 20, 2, 4), maxColorValue = 255),
rgb(c(255, 255, 254, 254, 254, 236, 204, 140), c(255, 247, 227, 196, 153, 112, 76, 45), c(229, 188, 145, 79, 41, 20, 2, 4), maxColorValue = 255),
rgb(c(255, 255, 254, 254, 254, 236, 204, 153, 102), c(255, 247, 227, 196, 153, 112, 76, 52, 37), c(229, 188, 145, 79, 41, 20, 2, 4, 6), maxColorValue = 255)
))
}
brewer_pal2 <- # modified from scales:::brewer_pal
function() { # stripped down all arguments, just to show the core
function(n) {
mybrewerpal(n, "mypal") ##modified, usually this is selected by a function
## with type and name as arguments, selecting a palette from a list called scales:::brewer
}
}
scale_fill_custom <- ### modified from scale_fill_brewer, removed some arguments
function (..., aesthetics = "fill") {
discrete_scale(aesthetics, "custom", brewer_pal2(), ...) ## give a new name to the
## scale, it will create a new Scale object.
}
p <-
ggplot(mtcars, aes(x = mpg, y = disp)) +
scale_fill_custom()
p + geom_point(shape = 21, aes(fill = as.factor(cyl)))
p + geom_point(shape = 21, aes(fill = as.factor(carb)))