4
votes

I'd like to produce a plot with reordered months on the x axis (instead of starting in Jan and ending in Dec, I'd like to start on Apr and end on Mar).

My data is something like:

          Month         An              Fiscal.Year Month.Number Month.Name
    1     2009-04-01    40488474        2009        4            Apr
    2     2009-05-01    53071971        2009        5            May
    3     2009-06-01    24063572        2009        6            Jun
    ...
    44    2012-11-01    39457771        2012        11           Nov
    45    2012-12-01    44045572        2012        12           Dec
    46    2013-01-01    90734077        2012        1            Jan

My code for producing the plot is:

g <- ggplot(data = data, aes(x = Month.Number, y = An)) +
     geom_line(aes(group = Fiscal.Year, colour = factor(Fiscal.Year))) +    
     scale_x_discrete(
       name = "Month", 
       breaks = data$Month.Number,
       labels = data$Month.Name
     ) +
     scale_y_continuous();

but the result is a plot ordered by month from Jan to Dec, not from Apr to Mar as I want. I've tried the limits option inside scale_x_discrete, but I think this just reorders the x axis labels, not the real data.

Could you please help me?

Thanks in advance for your answer!

2
please dput your data variable to reproduceagstudy

2 Answers

5
votes

You have to reorder the factor levels of Month.Name. Assuming dfis your data.frame:

df$Month.Name <- factor( df$Month.Name, levels = c( "Apr", "May", ..., "Feb", "Mar" ) )
g <- ggplot(data = df, aes(x = Month.Name, y = An) ) +
     geom_line(aes(group = Fiscal.Year, colour = factor(Fiscal.Year))) +    
     scale_x_discrete( name = "Month" ) +
     scale_y_continuous();

Alternatively you can just change Month.Number such that, Apr is 1, May is 2 and so on...

2
votes

Just run before plotting:

data$Month.Number <- ((data$Month.Number+8) %% 12) + 1