如何让ggplot自动提取调色板的组数

Phi*_* Wu 5 r ggplot2

ggplot在具有大量组(例如 n > 14)的对象上使用时,大多数调色板都无法应对。该函数colorRampPalette能够扩展范围,但要将其嵌入 中scale_fill_manual,您需要知道唯一组的数量。

有没有办法直接自动提取所需的颜色数量 ggplot?我在下面提供了一个示例,为了使调色板工作,我必须将组数 (14) 作为参数添加到scale_fill_manual(values = palette_Dark2(14)).

使用 scale_fill_brewer 绘图

df <- data.frame(group = paste0("Category", 1:14),
             value = 1:28)

library(ggplot2)
ggplot(df, aes(x = group, y = value, fill = group)) + 
  geom_bar(stat = "identity") +
  scale_fill_brewer(palette = "Set1")
Run Code Online (Sandbox Code Playgroud)

警告消息:在 RColorBrewer::brewer.pal(n, pal) 中:n 太大,调色板 Set1 允许的最大值为 9 返回您要求的调色板,具有这么多颜色

在此处输入图片说明

使用自定义调色板绘图

在这里,我在绘图之前指定了一个新的调色板,它是一个具有 14 步的色带。

library(RColorBrewer)
palette_Dark2 <- colorRampPalette(brewer.pal(14, "Dark2"))
Run Code Online (Sandbox Code Playgroud)

然后我在情节中使用它如下:

ggplot(df, aes(x = group, y = value, fill = group)) + 
  geom_bar(stat = "identity") +
  scale_fill_manual(values = palette_Dark2(14))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

更新:

我试图用来length(unique(group))提取唯一组的数量,但获得了一条错误消息

唯一(组)错误:找不到对象“组”

在尝试使用时length(unique(df$group)),错误信息是:

错误:手动刻度值不足。需要14个,但只提供1个。另外:警告消息:在 brewer.pal(length(unique(df$group)), "Dark2") 中:n 太大,调色板允许的最大值为 8 用这么多颜色返回您要求的调色板

Mic*_*per 4

我对我的上一个答案并不是 100% 满意,所以这个答案是以更 ggplot 的方式完成的。深入研究ggplot 包中的代码scales,有一个discrete_scale可以使用的函数:

library(ggplot2)
ggplot(df, aes(x = group, y = value, fill = group)) + 
  geom_bar(stat = "identity") +
  discrete_scale("fill", "manual", palette_Dark2)
Run Code Online (Sandbox Code Playgroud)

此代码将自动从指定的美学中提取组数,在本例中为“填充”。不需要手动指定组的数量,并且看起来相当健壮。例如,增加到包括 20 组:

df <- data.frame(group = paste0("Category", 1:20),
                 value = 10) 

ggplot(df, aes(x = group, y = value, fill = group)) + 
  geom_bar(stat = "identity") +
  discrete_scale("fill", "manual", palette_Dark2)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述