【问题标题】:ggplot2 - highlight min/max barggplot2 - 突出显示最小/最大条
【发布时间】:2011-12-12 20:15:21
【问题描述】:

在不向 data.frame 添加额外列的情况下,是否有一种内置方法可以突出显示最小/最大栏?在以下示例中,我希望 Joe 条为绿色(最大),而 John 条为红色(最小)。

我确定以前有人问过这个问题,但是我在搜索时找不到:

data= data.frame( Name = c("Joe","Jane", "John") , Value = c(3,2,1) )
ggplot(data=data)+geom_bar(aes_string(x="Name",y="Value"), stat="identity" )

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用子集:

    p <- ggplot(data=data)+
         geom_bar(aes(x=Name, y=Value), stat="identity") +
         geom_bar(data=subset(data, Value==min(Value)), aes(Name, Value),
                  fill="red", stat="identity") +
         geom_bar(data=subset(data, Value==max(Value)), aes(Name, Value),
                  fill="green", stat="identity")
    print(p)
    

    【讨论】:

      【解决方案2】:

      给你

      ggplot(data, aes(Name, Value)) + 
       geom_bar(stat = 'identity') + 
       geom_bar(stat = 'identity', aes(fill = factor(Value)), 
         subset = .(Value %in% range(Value))) +    
       scale_fill_manual(values = c('red', 'green'))
      

      【讨论】:

        【解决方案3】:

        我想我会使用ifelse 方法一次性完成所有操作:

        ggplot(data=data) + 
          geom_bar(aes_string(x="Name",y="Value", fill='factor(ifelse(Value==max(Value), 3, ifelse(Value==min(Value), 2, 1)))'), stat="identity" ) + 
          scale_fill_manual(values=c('gray20', 'red', 'green'), legend=F)
        

        【讨论】:

          【解决方案4】:

          这是通过which.min()which.max() 使用逻辑索引的一个选项:

          ggplot(data, aes(Name, Value, stat = "identity")) + 
            geom_bar() +
            geom_bar(data = data[which.min(data$Value),], fill = "red") +
            geom_bar(data = data[which.max(data$Value),], fill = "green")
          

          【讨论】:

          • 我认为只有在 @rcs 示例中添加 aes(...) 和 stat = "Identity" 时这才有效
          • @SFun28 - 我找不到参考,但在aes() 中设置的任何值都将传递给每个后续层,因此stat = "identity" 隐式提供给每个 geom_layer。
          • @SFun28 - 这也是我们不必明确传递NameValue 的原因。
          • 美学得到继承,但统计数据不是美学。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2022-08-05
          • 2021-10-04
          • 2020-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-14
          相关资源
          最近更新 更多