1
私は3つの異なる場所で時間の経過とともに種の存在量のスタックプロットを作成しました。 私が作成したコードは、異なるサイトの豊富さの順序に応じて異なる色の異なる種をプロットします。 どのようにして各サイトの同じ種に同じ色を割り当てるようにコードを適合させることができますか? 他の質問には、グラフ内で特定の順序を割り当てることが含まれます。これは、異なるループ間で同じ順序を維持したいという点で異なります。積み重なった棒グラフで色を割り当てる
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中の豊富なピンク種である。どこが間違っているか?私はまだバーの底にある最も支配的な種が必要ですが、私はすべてのループを通して同じ種に割り当てられたままにするために色をする必要があります。あなたはcols2a
にグループ名をASSINGする必要がしたいようscale_fill_manual(values = cols2a)
のために働く
'scale_fill_manual()'を試してください – Jimbou
[ggplot2 barplotのバーの順序と色]の可能な複製(https://stackoverflow.com/questions/17331892/order-and-color-of-bars-in-ggplot2- barplot)または[ここ](https://stackoverflow.com/questions/39684259/how-to-change-the-color-spectrum-pattern-of-fill-in-ggplot2-bar-chart) – Jimbou