我在三个不同的地点创建了随着时间推移的物种丰度堆积图。我创建的代码根据它们在不同地点的丰度顺序以不同的颜色绘制不同的物种。如何调整代码以将相同的颜色分配给每个站点中的相同物种。其他问题涉及在图表中分配特定顺序,这是不同的,因为我只想在不同的循环中保持相同的顺序。
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 中丰富的粉红色物种。我哪里错了?我仍然需要最主要的物种位于栏的底部,但我需要在所有循环中保持分配给同一物种的颜色。