geom_bar ggplot2 绘图类别但根据附加因素分配色标

geom_bar ggplot2 plotting category but assigning colour scales based on an additional factor

我想知道是否有任何方法可以调整 geom_bar 堆栈图的颜色,而不是绘制的组件?

澄清一下,我有一个包含四个组成部分的数据框:物种、计数、日期和类型。

   species count       date type
1        a    20 2016-05-22  Phy
2        b    34 2016-05-22  Phy
3        c    45 2016-05-22  Phy
4        d     4 2016-05-22  Zoo
5        e    43 2016-05-22  Zoo
6        f     9 2016-05-22 Bact
7        g    19 2016-05-22 Bact
8        h    32 2016-05-22 Bact
9        a    16 2016-05-23  Phy
10       b     0 2016-05-23  Phy
11       c     0 2016-05-23  Phy
12       d     2 2016-05-23  Zoo
13       e    42 2016-05-23  Zoo
14       f    23 2016-05-23 Bact
15       g    22 2016-05-23 Bact
16       h    21 2016-05-23 Bact

所以我的问题是我想在 ggplot 中绘制堆积条:

ggplot(df, aes(x = date, y=count, group = species, fill = Species)) + 
  geom_bar(stat = "identity")

但是,我希望条形的颜色由 "type" 确定,类型中的每个类别都有自己的色标。这样,如果物种 a-c 都在 "Phy" 类别中,物种 a、b 和 c 将是,例如,不同深浅的蓝色。

如有任何帮助,我们将不胜感激。

谢谢! 大号

这是一个按类型重新排序物种因素然后将不同的调色板拼接在一起的解决方案。如果您不喜欢生成的特定颜色,请选择不同的调色板。

library(forcats)
library(tidyverse)
library(scales)

# Reorder the levels of the species factor by type
df = df %>%
    mutate(species = fct_reorder(species, as.numeric(type)))
unique_df = df %>% distinct(type, species)
type_counts = table(unique_df$type)

colours = character(0)
# Need to manually fill this at least up to the number of types
palettes = c("Blues", "Greens", "Reds")

for (i in 1:length(type_counts)) {
    colours = c(colours, brewer_pal(palette = palettes[i])(type_counts[i]))
}

ggplot(df, aes(x = date, y=count, group = species, fill = species)) + 
    geom_bar(stat = "identity", colour = "black") +
    scale_fill_manual(values = colours) +
    theme_bw()

根据评论线程,这是一个解决方案,使用分面作为类型,使用颜色作为物种。在实践中它可能不如这个例子有效,这取决于数据中有多少日期、类型和物种。

ggplot(df, aes(date, count)) + 
  geom_col(aes(fill = species)) + 
  facet_grid(. ~ type) + 
  scale_fill_brewer(palette = "Spectral") +
  theme_light()

这种类型的数据更适合 slopegraph。这会向您显示堆叠条形图看不到的清晰模式。

例如,现在很明显,虽然细菌种类在第 1 天具有异质丰度,但处理导致它们在第 2 天收敛到单一丰度。植物都受到处理的有害影响,有些严重但 "a" 只是轻微的。这些动物几乎没有受到任何影响,保持了之前的群落结构。

require(dplyr)

ggplot(df, aes(date, count, group = species)) +
  facet_grid(type ~ .) +
  geom_line(aes(colour = type), size = 3, show.legend = F) +
  geom_line() +
  geom_text(data = function(x) {x %>% filter(date == min(date))},
            aes(label = species), nudge_x = -.025) + 
  theme_bw()