Moving the month leads to the x axis (ggplot)

I would like to create a chart with reordered months on the x axis (instead of starting in January and ending in December, I would like to start in April and ending 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 creating the graph:

 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 schedule assigned by months from January to December, and not from April to March, as I want. I tried the option of constraints inside scale_x_discrete, but I think it just reorders the x-axis labels, not the real data.

Could you help me?

Thanks in advance for your reply!

+4
source share
2 answers

You must change the order of the Month.Name levels. Assuming df is 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 simply change Month.Number so that in April it is 1, May is 2, and so on ...

+5
source

Just run before plotting:

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

All Articles