在堆积的条形图中分配颜色

时间:2017-07-26 12:24:39

标签: r loops ggplot2 colors cowplot

我在三个不同的地点创建了物种丰富度的叠加图。 我创建的代码根据不同位置的丰度顺序绘制不同颜色的不同物种。 如何调整代码以将相同的颜色分配给每个站点中的相同物种。 其他问题涉及在图中分配特定顺序,这是不同的,因为我只想在不同的循环中保持相同的顺序。

library(ggplot2)
library(cowplot)
library(plyr)
library(dplyr)
library(reshape2)
dat_all =  data.frame(year = rep(1:6, 15), site= rep(c("X","Y","Z"), each=6), 
species = rep(c("A","B","C","D","E"),each=3))

dat_all$abund= c(31, 36, 23, 23,4, 29, 9, 15,32, 28, 20, 1, 9, 17, 14, 2, 3, 
        27, 23, 28, 29, 33, 16, 22, 26, 27, 14, 9, 3, 14, 15, 13, 30, 30, 4, 
        16, 18, 14, 19, 16, 19, 10, 30, 24, 34, 32, 20, 12, 
        16, 21, 23, 17, 17, 17, 28, 16, 16, 13, 30, 23,24, 16, 6, 7, 21, 22, 
        23, 3, 12, 19, 19, 39, 6, 21, 21, 14, 12, 13, 13, 22, 10, 12, 24, 
        2,21, 25, 2, 12,30, 20)


cols2a= c("#c2c387","#74aff3","#f5dc9e", "#53c6ef","#f4b189")

for (s in unique(dat_all$site)){

dat = dat_all[dat_all$site == s, ]

dat$species = as.character(dat$species)

dat$species =
  factor(
    dat$species,
    levels =
      tapply(dat$abund, dat$species, sum) %>%
      sort %>%
      names
  )
# Aggregate to site / species
dat =
  ddply(
    dat,
    c("year", "species"),
    summarize,
    abundance = sum(abund)
  )

dat$year = factor(dat$year)

dat = dat[order(dat$year, -as.numeric(dat$species)), ]

#Add labels
dat=
  ddply(
    dat,
    c("year"),
    transform,
    pos = cumsum(abundance)
  )
dat$label = dat$species
dat$label[dat$abundance < 2] = NA


# ## Plot
g= ggplot(dat, aes(x =year, y = abundance)) +
  geom_hline(yintercept = 0, size = 0.25, colour = "darkgrey") +
  geom_bar(
    aes(fill = species),
    stat = "identity", colour = "black", size = 0.25
  ) +
  geom_text(
    aes(label = label, y = pos),
  vjust = 1.25, size = 2.5
  ) +
  scale_y_continuous(
    labels = round
  ) +
  ylab("Total abundance") +
  scale_fill_manual(
    values = cols2a,
    guide = FALSE
  ) +
  ggtitle( s ) +
  theme_bw() +
  theme(
    axis.title.x = element_blank(),
    axis.ticks.x = element_blank(),
    panel.border = element_blank(),
    panel.grid = element_blank()
  )

assign(paste0("plot",s), g)
}

plot_grid(plotX,plotY,plotZ)

如您所见,颜色会发生变化。例如,物种B更丰富并且在地点X中是粉红色的,但物种D是地点Y和地区中丰富的粉红色物种。 Z.我哪里错了?我仍然需要最优势的物种在酒吧的底部,但我需要颜色在所有循环中保持分配给相同的物种。

由于 enter image description here

1 个答案:

答案 0 :(得分:1)

您几乎就在那里,scale_fill_manual(values = cols2a)可以按照您的意愿工作,需要将群组名称分配给cols2a

cols2a = c("#c2c387","#74aff3","#f5dc9e", "#53c6ef","#f4b189")
names(cols2a) = levels(dat_all$species)

否则scale_fill_manual()按照绘图的顺序对组进行着色。