【发布时间】:2021-01-08 19:51:16
【问题描述】:
我正在使用 ggplot2 的 scale_fill_fermenter() 作为离散彩条图例。可以在 palette 参数下指定颜色,但似乎只有一组有限的调色板可用(来自RColorBrewer::display.brewer.all() 的调色板)。
有没有办法定义自定义调色板?传递颜色名称/十六进制向量的简单解决方案不起作用...
干杯!
【问题讨论】:
我正在使用 ggplot2 的 scale_fill_fermenter() 作为离散彩条图例。可以在 palette 参数下指定颜色,但似乎只有一组有限的调色板可用(来自RColorBrewer::display.brewer.all() 的调色板)。
有没有办法定义自定义调色板?传递颜色名称/十六进制向量的简单解决方案不起作用...
干杯!
【问题讨论】:
scale_fill_fermenter 是一个返回的包装器
binned_scale(aesthetics, "fermenter",
binned_pal(brewer_pal(type, palette, direction)),
na.value = na.value, guide = guide, ...)
如果您可以调用非导出函数ggplot2:::binned_pal,您可以使用此代码作为模板编写自定义scale_fill_fermenter 函数,该函数允许自定义调色板,可能如下所示:
library(ggplot2)
v <- ggplot(faithfuld) +
geom_tile(aes(waiting, eruptions, fill = density))
# Custom palette
pal <- scales::hue_pal()(8)
scale_fill_fermenter_custom <- function(pal, na.value = "grey50", guide = "coloursteps", aesthetics = "fill", ...) {
binned_scale("fill", "fermenter", ggplot2:::binned_pal(scales::manual_pal(unname(pal))), na.value = na.value, guide = guide, ...)
}
v + scale_fill_fermenter_custom(pal)
【讨论】: