首页 > 解决方案 > R order geom_bar 基于一个级别

问题描述

如何根据变量的第一级订购条形图var现在订单是两个条的总和,我希望它只按valuewhere varis排序"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 )

标签: rggplot2geom-bar

解决方案


无需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")

在此处输入图像描述


推荐阅读