【问题标题】:Setting a conditional color by stat_summary in ggplot在ggplot中通过stat_summary设置条件颜色
【发布时间】:2016-07-04 15:54:34
【问题描述】:

所以我试图通过 ggplot 中的统计摘要函数设置条件颜色。我正在 ggplot 中创建一个均值条形图,并希望设置一个条件颜色,如果平均值小于 0,则将其设为红色,如果高于 0,则将其设为绿色。

Name      Value
A         10
A         -5
B         15
B         12
C         -2
C         -4

ggplot(data, aes(x=Name, y=Value, group=Name))+
stat_summary(fun.y="mean", geom="bar")

我知道我需要一个 ifelse 语句,但我不确定条件是什么。

【问题讨论】:

    标签: r ggplot2 colors


    【解决方案1】:

    如果您在使用 ggplot 之前为绘图准备数据会容易得多,因为您的情况是事先汇总数据然后使用 geom_bar 应该相当简单:

    dataSum <- aggregate(Value ~ Name, data, FUN = 'mean')
    ggplot(dataSum, aes(x = Name, y = Value, fill = (Value > 0))) + 
           geom_bar(stat = "identity", position = 'dodge') + 
           scale_fill_manual(labels = c("FALSE" = "Less than zero", "TRUE" = "Above zero"), 
                             values = c('red', 'green')) + 
           theme(legend.title = element_blank())
    

    【讨论】:

      【解决方案2】:
      # Prepare data: split the data into subsets and compute summary using aggregate
        data <- aggregate(Value ~ Name, data, FUN = 'mean')
      # Plot
        g <-  ggplot( data , aes(x=Name, y=Value, group=Name)) + 
        # Add condition for colors aes(fill = Value > 0 )
        stat_summary(fun.y="mean", geom="bar",aes(fill = Value > 0 ))
        g + scale_fill_manual(values = c('red', 'green'))
      

      还有输出:

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-19
        • 1970-01-01
        • 2022-08-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        相关资源
        最近更新 更多