2

I am trying to reorder the graph bars based on one of the variables, in this case the y variable in descending order instead of the alphabetical order of x.

x<-c("Jan","Feb","Mar")
y <- c(2000, 23400, 26800)
z<-c(1100,5000,6000)
df<-data.frame(x,y,z)
View(df)

library(reshape2)
library(ggplot2)

df.long<-melt(df)
ggplot(df.long,aes(x=x, y=value,fill=variable))+geom_col(position = "dodge", width=0.9)

The current plot that I have is this:

I am hoping to plot a graph like this below:

The first plot is before reordering using the script above, and I am hoping to plot a graph similar to the second one. I would really appreciate some guidance here. Thank you.

Sue
  • 57
  • 1
  • 7

1 Answers1

3

Try this. You can use reorder() function to arrange data in x based on the reshaped values. Here the code:

library(reshape2)
library(ggplot2)

#Data
df.long<-melt(df)
#Plot
ggplot(df.long,aes(x=reorder(x,-value),
                   y=value,fill=variable))+
  geom_col(position = "dodge", width=0.9)+
  xlab('Month')+
  theme(legend.position = 'bottom')

Output:

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84