使用scale_fill_binned()时如何使用特定的填充颜色?

How to use specific filling colors when using scale_fill_binned()?

我想在使用带有 ggplot 代码的函数 scale_fill_binned() 时使用我自己的填充颜色(例如:c("red", "blue", "grey50", "black"))。我该怎么做?

这是一个最小的可重现示例:

library(tidyverse)

dat <- mtcars %>% 
       group_by(cyl) %>% 
       summarise(n = n(),
                 mean_hp = mean(hp)) %>% 
       ungroup

ggplot(data = dat, aes(x = cyl, y = mean_hp, size = n, fill = n)) +
  geom_point(shape = 21) +
  scale_size_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T)) +
  scale_fill_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T), type = "viridis") +
  labs(x = "Cylinder", y = "Mean hp", fill = "Nb of cars", size = "Nb of cars") +
  theme_minimal()

输出结果如下:

要使用这一系列函数,您需要提供一个函数,该函数 returns 是一个具有 class "ScaleContinuous" "Scale" "ggproto" "gg" 的对象(即等效于 scale_fill_viridis_c 的输出)!

scale_fill_custom <- function (..., alpha = 1, begin = 0, end = 1, direction = 1, 
  option = "D", values = NULL, space = "Lab", na.value = "grey50", 
  guide = "colourbar", aesthetics = "fill") {
  continuous_scale(aesthetics, scale_name = "custom", 
    palette = scales:::gradient_n_pal(c("red", "blue", "grey50", "black"), 
    values, space), na.value = na.value, 
    guide = guide, ...)
}
ggplot(data = dat, aes(x = cyl, y = mean_hp, size = n, fill = n)) +
  geom_point(shape = 21) +
  scale_size_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T)) +
  scale_fill_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T), 
    type = scale_fill_custom) +
  labs(x = "Cylinder", y = "Mean hp", fill = "Nb of cars", size = "Nb of cars") +
  theme_minimal()

请注意,您使用的颜色作为一种尺度,可以通过眼睛将其转化为具有数字意义的差异。颜色是在手动应用的点之间插入的,因此实际上不会是您的确切颜色。如果您希望按颜色划分平均值,最好创建一个因子,然后手动应用您的主题。

ggplot(data = mutate(dat, n = cut(n, breaks = c(0, 8, 10, 12, 20))), 
  aes(x = cyl, y = mean_hp, size = n, fill = n)) +
  geom_point(shape = 21) +
  scale_size_discrete() +
  scale_fill_manual(values = c("red", "blue", "grey50", "black")) +
  labs(x = "Cylinder", y = "Mean hp", fill = "Nb of cars", size = "Nb of cars") +
  theme_minimal()

通过@teunbrand 的评论,我想出了一些办法。

cols <- c("red", "blue", "grey50", "black")
ggplot(data = dat, aes(x = cyl, y = mean_hp, size = n, fill = n)) +
  geom_point(shape = 21) +
  scale_size_binned(breaks = c(8, 10, 12), guide = guide_bins(show.limits = T)) +
  labs(x = "Cylinder", y = "Mean hp", fill = "Nb of cars", size = "Nb of cars") +
  theme_minimal() +
  binned_scale(aesthetics = "fill", scale_name = "custom", 
               palette = ggplot2:::binned_pal(scales::manual_pal(values = cols)),
               guide = "bins",
               breaks = c(8, 10, 12), limits = c(min(dat$n), max(dat$n)), show.limits = T)

输出结果如下: