1

Using R, I want bars in a bar chart in a certain order.

The order is:

a<-c("no exercise", "strength", "moderate aerobics", "moderate aerobics + strength", "high aerobics")

And then the values, let's just say:

b<- c(10, 20, 25, 40, 40)
df<-data.frame(a, b)

When creating a bar plot, the order of bars is alphabetic, rather than the original:

ggplot(df) +
  geom_bar( aes(x=a, y=b), stat="identity", fill="red")

[enter image description here][1] Is there a way to change that?

[1]: https://i.stack.imgur.com/sZDXc.png## Heading ##

Gal Levin
  • 39
  • 7

1 Answers1

0

If we want to reorder it in the same order of occurence, use factor with levels specified as the unique values of the column (here, we have only unique values but we use unique as a general case where the unique will get the unique values on the order of its occurrence)

library(dplyr)
library(ggplot2)
df %>% 
  mutate(a = factor(a, levels = unique(a))) %>% 
  ggplot() + 
     geom_bar(aes(x = a, y = b), stat = 'identity', fill = 'red')
akrun
  • 874,273
  • 37
  • 540
  • 662