I have a df:
df1 <- data.frame(ID = c('a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1',
'a', 'b', 'c', 'c1', 'd', 'e', 'f', 'g', 'h', 'h1'),
val = c(22, 15, 14, 17, 13, 16, 15, 12, 11, 12, 12, 16,
16, 16, 14, 17, 16.5, 13, 12, 12),
time = c("time1", "time1", "time1", "time1", "time1", "time1",
"time1", "time1", "time1", "time1","time2", "time2",
"time2", "time2", "time2", "time2", "time2", "time2",
"time2", "time2"))
And I want to reorder the bars in ascending order of val but when time==time1, whereas at present I think the below orders the bars based on cumulative val at time1+time2:
ggplot(df1, aes(x=reorder(ID, val), y=val, fill=time)) +
geom_bar(stat="identity", width=0.5, position=position_dodge())
>Solution :
Sometimes it’s convenient to sort the data.frame itself, then use fct_inorder to use that order directly:
library(forcats)
library(dplyr)
arrange(df1, time, val) |>
ggplot(aes(fct_inorder(ID), y=val, fill=time)) +
geom_col(width=0.5, position=position_dodge())
Alternatively, use fct_reorder2:
ggplot(df1, aes(fct_reorder2(ID, desc(time), desc(val)), y=val, fill=time)) +
geom_col(width=0.5, position=position_dodge())
