ggplot randomly formatting x-axis data.

Hello,

I have been struggling with getting ggplot to place data in a meaningful way along the x axis of a chart. (I would like to show the months of October thru September, from left to right, along the axis). So far, I have been unsuccessful. Have any of you come across this situation? I have place a couple of screen shots below, to help explain.

ggplot is formatting the x-axis in alphabetical order. You can convert month to factor class to set the order you want. For example:

combined_trips_3a %>%
  mutate(month = factor(month, levels=month.name[c(10:12,1:9)])) %>%
  ggplot( ...

month.name is a built-in vector of the months of the year, in calendar order.

Thank you Joel!! I will give this a shot tonight.

The factor() function from base R will order the levels alphabetically unless you specify an order, but the as_factor() function from the forcats package (part of the tidyverse) defaults to the order of appearance, which is what you want in this case.

factor(c("Winter", "Spring", "Summer", "Fall", "Winter", "Spring"))
#> [1] Winter Spring Summer Fall   Winter Spring
#> Levels: Fall Spring Summer Winter

forcats::as_factor(c("Winter", "Spring", "Summer", "Fall", "Winter", "Spring"))
#> [1] Winter Spring Summer Fall   Winter Spring
#> Levels: Winter Spring Summer Fall

Created on 2023-12-08 with reprex v2.0.2

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.