简体   繁体   English

R:按以下两个因素之一的值对geom_bar(stat =“ identity”,position = position_dodge())重新排序

[英]R: reorder geom_bar(stat = “identity”, position=position_dodge()) by value of one of two factors

I have a toy data.table 我有一个玩具数据表

library(data.table)
library(ggplot2)

set.seed(45L)
DT <- data.table(V1=c(1L,2L),
               V2=LETTERS[1:3],
               Value=c(1,3,5,3,2,4,6,7,7,5,4,2),
               V4=c(1,1,2,2,3,3,4,4,5,5,6,6))

And ggplot code 和ggplot代码

ggplot(DT, aes(x=factor(V4), y=V3, fill= factor(V1)))+
geom_bar(stat = "identity", position=position_dodge())+
theme(axis.text.x = element_text(angle = 45, hjust = 1),
      axis.line.x = element_line(),
      axis.line.y = element_line(),
      panel.background = element_blank())

Which results in the following plot 结果如下图

样例图

I would like to reorder the x-axis by the value of V1 factor 1. So, the resulting order would be 5,4,2,6,3,1. 我想通过V1因子1的值对x轴重新排序。因此,结果顺序将为5,4,2,6,3,1。

Any help would be greatly appreciated! 任何帮助将不胜感激!

Your ordering depends on two other variables, so you can use forcats::fct_reorder2() : 您的排序取决于其他两个变量,因此可以使用forcats::fct_reorder2()

library(forcats)

ggplot(DT, aes(x=fct_reorder2(factor(V4), V1, Value, function(x, y) {sum(y[x == 1])}), 
               y=Value, fill= factor(V1)))+
    geom_bar(stat = "identity", position=position_dodge())+
    labs(x = "V4") +
    theme(axis.text.x = element_text(angle = 45, hjust = 1),
          axis.line.x = element_line(),
          axis.line.y = element_line(),
          panel.background = element_blank())

在此处输入图片说明

I typically do this sort of data prep in a pipeline prior to calling ggplot. 我通常在调用ggplot之前在管道中进行这种数据准备。 So: 所以:

DT[, .SD
   ][, V1Val := Value[V1 == 1], V4
   ][order(-V1Val, V4)
   ][, V4 := factor(V4, levels=unique(V4))
   ][, V1 := factor(V1)
   ][, ggplot(.SD, aes(x=V4, y=Value, fill=V1))
   + geom_bar(stat="identity", position=position_dodge())
   + theme(axis.text.x=element_text(angle=45, hjust=1),
           axis.line.x=element_line(),
           axis.line.y=element_line(),
           panel.background=element_blank())
   ]       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM