【问题标题】:Set common legend for multiple categoric plots ggplot 2为多个分类图ggplot2设置公共图例
【发布时间】: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\')

}

    标签: r ggplot2


    【解决方案1】:

    添加这个有效:

    scale_fill_manual(values = colLegend)
    

    【讨论】:

      猜你喜欢
      • 2016-10-20
      • 2021-05-22
      • 2021-10-21
      • 2016-05-21
      • 1970-01-01
      • 2020-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多