【发布时间】:2022-08-18 15:56:50
【问题描述】:
我在 for 循环中创建了五个图,它们是堆叠的列。有 10 个数字是从 0 到 9 的因子。不是每个图都有这些因子,但我希望有共同的颜色。例如所有的 1 都是蓝色的,所有的 9 都是绿色的。
IE。如果我有这个颜色列表,我如何将它应用于绘图。
colLegend <- list(\'0\' = \'#A9CCE3\', # light blue
\'1\' = \'#A3E4D7\', # light green
\'2\' = \'#27AE60\', # DARK GREEN
\'3\' = \'#F7DC6F\', # YELLOW
\'4\' = \'#F8C471\', # ORANGE
\'5\' = \'#D35400\', # RED
\'6\' = \'#117864\', # DARK TEAL
\'7\' = \'#AF7AC5\', # PURPLE
\'8\' = \'#2E4053\', # NAVY
\'9\' = \'#616A6B\') # GREY
当前代码
## plot stacked percentage of each value
labels <- c(\'19\', \'20\', \'22\')
# create tally of each Ellenberg value
j = 1
for (df in ellenCatTab){
dfName <- names(ellenCatTab)[j]
j = j + 1
df = df[,5:31]
tidy <- df %>%
gather(key=\'Quadrat\', value=\'Ellenberg\')
tidy <- na.omit(tidy)
tally <- tidy %>%
count(Quadrat, Ellenberg)
tally$Ellenberg <- as.factor(tally$Ellenberg)
tally <- as.data.table(tally)
tally[, c(\'Q\', \'Year\') := tstrsplit(tally$Quadrat, \"_\", fixed=TRUE)][]
tally$Q <- sub(\'X\', \'Q\', tally$Q)
stacked <- ggplot(tally, aes(fill=Ellenberg, y=n, x=Quadrat)) +
geom_bar(position=\'stack\', stat=\'identity\') +
ggtitle(dfName) +
labs(x=\'Year\', y=\'Number of Plants\') +
scale_x_discrete(labels=labels) +
theme_classic() +
facet_wrap(~ Q, nrow=1, scales=\'free_x\')
plot(stacked)
ggsave(plot=stacked,
file=paste0(dfName, \'_stacked.png\'),
limitsize=FALSE,
width=250, height=200, units=\'mm\')
}