geom_bar ggplot2绘制类别,但根据其他因素指定颜色比例

时间:2017-05-30 23:17:59

标签: r ggplot2 colors geom-bar stacked-chart

我想知道是否还有调整如何使用与绘制的组件不同的组件为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")

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

任何帮助都将不胜感激。

谢谢! →

3 个答案:

答案 0 :(得分:2)

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

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

Plot

答案 1 :(得分:2)

这是一个根据评论主题的解决方案,使用facet作为物种的类型和颜色。在实践中,它可能不如此示例有效,具体取决于数据中有多少日期,类型和种类。

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

enter image description here

答案 2 :(得分:0)

此类数据更适合slopegraph。这将显示清晰的图案,这些图案在堆叠条形图中不可见。

例如,现在显而易见的是,虽然细菌种类在第1天具有异质丰度,但是处理使它们在第2天收敛到单一丰度。植物都受到处理的有害影响,一些严重但“一个“只是轻微的。这些动物几乎没有受到影响,保留了以前的社区结构。

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

enter image description here

相关问题