基于一个级别的R阶几何图形条

基于一个级别的R阶几何图形条,r,ggplot2,geom-bar,R,Ggplot2,Geom Bar,如何根据变量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)

如何根据变量
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 )
库(“ggplot2”)
ct这应该可以

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)

使用
forcats::fct_reorder2()
您不需要修改
数据。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")