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

问题描述

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

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

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,guide = guide_bins(show.limits = T),type = "viridis") +
  labs(x = "Cylinder",y = "Mean hp",fill = "Nb of cars",size = "Nb of cars") +
  theme_minimal()

输出如下:

enter image description here

解决方法

要使用这一系列函数,您需要提供一个函数,该函数返回一个类为 def characters(a=""): character_keys = list(Characters.keys()) if a: return character_keys else: print(character_keys) 的对象(即等效于 "ScaleContinuous" "Scale" "ggproto" "gg" 的输出)!

scale_fill_viridis_c

Scatter plot of mtcars showing points filled with custom colours from continuous range

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

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,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()

Scatter plot of mtcars showing points filled with custom colours from discrete scale

,

通过@teunbrand 的评论,我能够想出一些东西。

cols <- c("red","black")
ggplot(data = dat,guide = guide_bins(show.limits = T)) +
  labs(x = "Cylinder",size = "Nb of cars") +
  theme_minimal() +
  binned_scale(aesthetics = "fill",palette = ggplot2:::binned_pal(scales::manual_pal(values = cols)),guide = "bins",breaks = c(8,limits = c(min(dat$n),max(dat$n)),show.limits = T)

输出如下:

enter image description here