0

I am trying to plot a line chart using ggplot but I can't seem to get the months in the x-axis in chronological order instead of alphabetical. Any help is greatly appreciated. This is my current code:

df <- data.frame(Months=c("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November","December"),
                Attacks=c(49, 70, 49, 44, 53, 35, 33, 36, 47, 40, 44, 32))

ggplot(data=df, aes(x=Months, y=Attacks, group=1)) +
  geom_line()+
  geom_point()
  • Just about every question involving `ggplot2` and "axis order" is resolved with `factor`s. It will order strings alphabetically unless you tell it the order explicitly (which you haven't attempted here). To do that, factor them and control the levels. – r2evans May 25 '21 at 15:20
  • Links that relate, in addition to the dupe link: https://stackoverflow.com/a/41206357/3358272, https://stackoverflow.com/q/66606315/3358272, https://stackoverflow.com/q/3253641/3358272. – r2evans May 25 '21 at 15:29

1 Answers1

1

The answer with ggplot2 is almost always factor.

In this case, all of the months are explicitly as listed in one of R's base datasets, month.name:

### validate my assumption *here*
all(df$Months %in% month.name)
# [1] TRUE

### convert to a factor, order defined by `month.name`
df$Months <- factor(df$Months, levels=month.name)

ggplot with months in the correct order

r2evans
  • 141,215
  • 6
  • 77
  • 149