0

I spent several hours searching for reordering a grouped bar chart on stackoverflow.com but I did not find the answer I was looking for. I want to change the order of the bars and legend to print 'before', 'during' and 'after' in that order but R keeps printing the factors alphabetically like this 'after' before' during' and don't know how to fix it.

If someone can help me, I will be thankful!

This is the order R displays which I want to change. enter image description here

Here is my code:

df <- data.frame(time = c("after","before","during","before","after","before","during","after","after","during", "during","after","before","during","before"),
variable = c("granny", "red del", "other", "golden", "star", "granny", "red del", "other", "golden", "star", "granny", "red del", "other", "golden", "star"),
value = c(34,66,7,12,99,35,66,82,55,48, 27,55,82,42,26))

df$time = as.factor(df$time)
df$variable = as.factor(df$variable)

ggplot(df, aes(x = variable, y = value, fill = time)) + 
geom_bar(position='dodge', stat='identity') +
theme_minimal() +
labs(x=' ', y=' ', title=' ') +
theme(plot.title = element_text(hjust=0.5, size=20, face='bold')) +
theme_bw() + 
theme(axis.line = element_line(color='black'),
plot.background = element_blank(),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank())
ithoughtso
  • 103
  • 8

1 Answers1

2

ggplot will just order any character variable alphabetically if there is nor specified order. To specify order of factor levels, the easiest approach would be just to state the order of levels in the factor function.

df$time = factor(df$time,levels = c("before","during", "after"))

instead of

df$time = as.factor(df$time)

enter image description here

user12256545
  • 2,755
  • 4
  • 14
  • 28
  • Thank you! it worked! To be honest, my code was originally in wide format but when I converted to long format, R converted time to a factor which seemed correct to meso I left it and tried other solutions online but I guess they cannot override the initial factor assignment? – ithoughtso Apr 28 '23 at 23:20