r-为多个分类图设置通用图例ggplot 2

  • 本文关键字:ggplot 设置 分类 r ggplot2
  • 更新时间 :
  • 英文 :


我正在for循环中创建五个堆叠列的绘图。有10个数字是从0到9的因子。不是每个情节都有这些因素,但我希望有共同的色彩。例如,所有1都是蓝色,所有9都是绿色。

也就是说,如果我有这个颜色列表,我该如何将它应用到绘图中。

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')
}

添加此项有效:

scale_fill_manual(values = colLegend)

最新更新