0
votes

I have a bar graph with two variables plotted on the same axis. I have melted data into long format, how do I reorder the bars based on one specific variable which is "Age" in a descending order? In long format, both "Age and Weight" variables fall under the "value" column, so it is not possible to reorder "Age" by reordering "value". Is there another way around this?

Group<-c("X1","Y1","Z1")
Age <- c(10, 15, 20)
Weight<-c(50,40,45)
df<-data.frame(Group,Age,Weight)

library(reshape2)
library(ggplot2)
df.long<-melt(df)

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

Reordering the values of both variables does not help, it reorders based on sum of two variables: enter image description here

what I really want is something similar to the graph below where the "Age" variable is in descending order, with the corresponding "Weight" variable. enter image description here

Thank you in advance.

1

1 Answers

0
votes

You can adjust the factor levels in Group based on value :

library(dplyr)
library(ggplot2)

df.long %>%
  arrange(variable, desc(value)) %>%
  mutate(Group = factor(Group, levels = unique(Group))) %>%
  ggplot() + aes(x=Group,y=value,fill=variable) +
  geom_col(position = "dodge", width=0.9)

enter image description here