【问题标题】:R order geom_bar based on one levelR order geom_bar 基于一个级别
【发布时间】:2020-02-10 13:09:34
【问题描述】:

如何根据变量var 的第一级对条形图进行排序? 现在订单是两个条的总和我想要它仅按value 排序,其中var"first"。下面是一个工作示例。

library("ggplot2")
ct <- rep(c("A", "B", "C", "D"),  2)
var <- c("first","first","first","first","second","second","second","second")
value <- c(1,5,0.5,8,2,11,0.2,0.1)

df <- data.frame(ct, var, value)
df

ggplot() +
  geom_bar(data = df
           , aes(x = reorder(ct, value)
                 , y = value
                 , fill = var
           )
           , stat = "identity"
           , position = "dodge"
           , width = .90 )

【问题讨论】:

    标签: r ggplot2 geom-bar


    【解决方案1】:

    使用forcats::fct_reorder2(),您无需修改​​您的data.frame

    library(ggplot2)
    library(forcats)
    
    ggplot() +
      geom_bar(data = df
               , aes(x = forcats::fct_reorder2(ct, var=='first', value, .desc = F)
                     , y = value
                     , fill = var
               )
               , stat = "identity"
               , position = "dodge"
               , width = .90 ) + labs(x = "ct")
    

    【讨论】:

      【解决方案2】:

      应该这样做。

      df %>% # take the dataframe and then...
          group_by(ct) %>% # per group...
          mutate(order = sum(value * (var == "first"))) %>% # you calculate the sum of value where var is "first"
          ggplot(aes(reorder(ct, order) # ...and then plot everything.
                     , value
                     , fill = var)) +
          geom_bar(stat = "identity"
                   , position = "dodge"
                   , width = .9)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-10
        • 2020-04-01
        • 1970-01-01
        • 2019-10-08
        • 1970-01-01
        • 2020-04-29
        • 1970-01-01
        • 2015-10-05
        相关资源
        最近更新 更多