【问题标题】:How to use conditional statement to colour barplot [duplicate]如何使用条件语句为条形图着色[重复]
【发布时间】:2021-03-04 06:00:36
【问题描述】:

我正在尝试根据样本编号ifelse(total > 90, "#FC2D00", "#008EFC")geom_bar 着色。换句话说,如果total > 90,条形应该是red,但total

type = c("aa", "bb", "cc")
total = c(110, 90, 89)

df = data.frame(type, total)

df %>% 
ggplot2::ggplot(aes(x = type, y = total)) +
  geom_bar(position = "dodge",
           stat = "identity")

我试过了

df %>% 
ggplot2::ggplot(aes(x = type, y = total)) +
  geom_bar(position = "dodge",
           stat = "identity",
           fill = (ifelse(
           levels(studies$total > 90, "#FC2D00", "#008EFC"))))

还有

df %>% 
mutate(fill = ifelse(levels(total > 90, "#FC2D00", "#008EFC"))) %>% 
ggplot2::ggplot(aes(x = type, y = total)) +
  geom_bar(position = "dodge",
           stat = "identity",
           fill = fill)

但它仍然无法正常工作。我不确定是什么问题。

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    将您的填充移到aes() 内。

    你应该在scale_fill_manual()中指定颜色:

    df %>% 
    mutate(fill = ifelse(levels(total > 90, "#FC2D00", "#008EFC"))) %>% 
    ggplot2::ggplot(aes(x = type, y = total, fill = fill)) +
      geom_bar(position = "dodge",
               stat = "identity") +
      scale_fill_manual(values= c("red","blue"))
    

    【讨论】:

    • 非常感谢本。当我试图复制你的代码时,它给了我一个错误Problem with `mutate()` input `fill`` 。还是谢谢你
    • 但我不知道scale_fill_manual() 的用途。谢谢:)
    【解决方案2】:

    在 ggplot 中,我们通常在刻度中定义颜色值,并且图例会根据数据很好地自动生成。因此,将您想要的图例标签放入数据中,而不是您想要使用的颜色。

    df %>% 
    mutate(emphasize = ifelse(total > 90, "> 90", "<= 90")) %>% 
    ggplot(aes(x = type, y = total, fill = emphasize)) +
      geom_col(position = "dodge") +
      scale_fill_manual(values = c("> 90" = "#FC2D00", "<= 90" = "#008EFC"))
    

    我们不需要使用levels() - 这是一个糟糕的选择,因为total 不是一个因素(并且它不会每行返回一个值,它可能具有与数据不同的顺序.. .)。我还将geom_bar 切换为geom_col - geom_col 具有stat = "identity" 作为默认值。

    【讨论】:

    • 感谢 Gregor 的详细解释。它现在正在工作,但我不想生成图例。我试过geom_col(aes(fill = ifelse(totalSamples &gt; 4000, "#FC2D00", "#008EFC"))),它也可以工作。非常感谢
    【解决方案3】:

    不需要ifelse()mutate()。您可以直接使用fill 中的逻辑条件,然后使用scale_fill_manual() 格式化颜色和标签:

    library(ggplot2)
    library(dplyr)
    #Data
    type = c("aa", "bb", "cc")
    total = c(110, 90, 89)
    df = data.frame(type, total)
    #Plot
    df %>% 
      ggplot2::ggplot(aes(x = type, y = total,fill=total > 90)) +
      geom_bar(position = "dodge",
               stat = "identity")+
      scale_fill_manual(values = c("#FC2D00","#008EFC"),
                        labels=c('TRUE'='>90','FALSE'='<90'))+
      labs(fill='Total')
    

    输出:

    【讨论】:

    • 哦,我不知道你可以使用 scale_fill_manual 。太棒了 :) 非常感谢鸭子
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-28
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多