2

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(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

Example 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.

Any help would be greatly appreciated!

Stephen Williams
  • 561
  • 4
  • 12
  • I wonder if [this question](https://stackoverflow.com/questions/3253641/change-the-order-of-a-discrete-x-scale/41277240#41277240) helps you. – jazzurro Jun 16 '17 at 00:03
  • thanks but unfortunately this doesn't seem to be helpful when you have two factors and must be able to choose one to reorder by. – Stephen Williams Jun 16 '17 at 00:13

2 Answers2

3

Your ordering depends on two other variables, so you can use 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())

enter image description here

Marius
  • 58,213
  • 16
  • 107
  • 105
0

I typically do this sort of data prep in a pipeline prior to calling 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())
   ]       
Clayton Stanley
  • 7,513
  • 9
  • 32
  • 46