【问题标题】:legend box color changes if 2 legends in ggplot如果 ggplot 中有 2 个图例,图例框颜色会发生变化
【发布时间】:2021-08-20 11:53:51
【问题描述】:

我正在尝试根据以下df生成一个ggplot

df <- data.frame(
  Input = c("S1", "S2", "S3", "S4"),
  Brand = c("Brand01", "Brand01", "Brand01", "Brand01", "Brand02","Brand02","Brand02","Brand02"),
  Average = c(21.52027, 21.60699, 20.77871, 21.22759, 25.05574, 22.74372, 22.80795, 22.98509),
  Limit = c(31.89098, 31.89098, 31.89098, 31.89098, 31.57953, 31.57953, 31.57953, 31.57953))

p = ggplot(df, aes(x=Input, y=Average, fill=Brand)) +
       facet_wrap(~ Brand, ncol = 2) +
       geom_bar(stat="identity", position=position_dodge(), colour="black", width = 0.9, show.legend = FALSE) +
       xlab("Input") + ylab("Average") +
       theme(axis.title.x = element_text(size=14), axis.title.y = element_text(size=14),
             legend.text = element_text(size=14), plot.title = element_text(size = 20, face = "bold"),
             axis.text.x = element_text(size=6))+ 
       theme(axis.text.x = element_text(angle = 90)) +
       geom_hline(aes(yintercept=Limit, linetype = "dashed"), color = "red") +
       scale_linetype_manual(name = "Limit", values = "dashed", labels = "")

show.legend = FALSE 时,情节看起来像 但是当我有show.legend = TRUE 然后限制框改变颜色,我想让它像第一个情节一样“灰色”或白色。 我尝试了其他相关主题的一些技巧,但没有任何效果。

【问题讨论】:

    标签: r ggplot2 legend


    【解决方案1】:

    因为您在主 ggplot2 调用中声明了 fill = Brand,所以它被每一层继承。如果将其移动到geom_bar() 层,则图例应该会合理显示。

    library(ggplot2)
    
    df <- data.frame(
      Input = c("S1", "S2", "S3", "S4"),
      Brand = c("Brand01", "Brand01", "Brand01", "Brand01", "Brand02","Brand02","Brand02","Brand02"),
      Average = c(21.52027, 21.60699, 20.77871, 21.22759, 25.05574, 22.74372, 22.80795, 22.98509),
      Limit = c(31.89098, 31.89098, 31.89098, 31.89098, 31.57953, 31.57953, 31.57953, 31.57953))
    
    ggplot(df, aes(x=Input, y=Average)) +
      facet_wrap(~ Brand, ncol = 2) +
      geom_bar(aes(fill=Brand), stat="identity", position=position_dodge(), colour="black", width = 0.9) +
      xlab("Input") + ylab("Average") +
      theme(axis.title.x = element_text(size=14), axis.title.y = element_text(size=14),
            legend.text = element_text(size=14), plot.title = element_text(size = 20, face = "bold"),
            axis.text.x = element_text(size=6))+ 
      theme(axis.text.x = element_text(angle = 90)) +
      geom_hline(aes(yintercept=Limit, linetype = "dashed"), color = "red") +
      scale_linetype_manual(name = "Limit", values = "dashed", labels = "")
    

    reprex package (v1.0.0) 于 2021-08-20 创建

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2021-10-29
      • 1970-01-01
      • 2022-06-22
      • 2017-01-16
      • 2016-12-29
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多