-1

I have a pretty large dataframe with observations from 1985 to date for the months May-September like the example :

month<-c("May","June","July","August","September","May","June","July","August","September")
 year<-c("1985","1985","1985","1985","1985","1986","1986","1986","1986","1986")
 value<-c(2,6,4,5,9,7,2,6,5,4)
 df<-data.frame(month,year,value)

When I try to plot the data grouped by the year, the order of months change. I have tried to order the data and set the month column as a factor but still, I get the following result.

ggplot(df, aes(x=month, y=value,group=year))+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
                                                           ,panel.grid.minor = element_blank()) +ylim(0,10)+labs(x="Month",y=expression(bold(paste("variable here"))))+
    theme(axis.title.x = element_text(face="bold", size=12),axis.text.x = element_text(size=9))+
    theme(axis.title.y = element_text(face="bold", size=12),axis.text.y = element_text(size=9))+theme(axis.text.x = element_text(angle = 45, hjust = 1))+
    geom_line(linetype="solid", size=1)+geom_point(color="gray7", size=2,shape=15)

Any ideas how to solve this?I want to keep the order of my column (May, June, July, August, September)

Thanks

geo_dd
  • 283
  • 1
  • 5
  • 22

1 Answers1

1

Setting month as a factor and specifying the order of the levels (with the argument levels) solves the issue, as below.

month<-c("May","June","July","August","September","May","June","July","August","September")
    year<-c("1985","1985","1985","1985","1985","1986","1986","1986","1986","1986")

value<-c(2,6,4,5,9,7,2,6,5,4)

df<-data.frame(month,year,value)

df$month <- factor(df$month, levels = c("May", "June", "July", "August", "September"))

ggplot(df, aes(x=month, y=value,group=year))+theme_bw()+theme(plot.background = element_blank(),panel.grid.major = element_blank()
                                  ,panel.grid.minor = element_blank()) +ylim(0,10)+labs(x="Month",y=expression(bold(paste("variable here"))))+
    theme(axis.title.x = element_text(face="bold", size=12),axis.text.x = element_text(size=9))+
    theme(axis.title.y = element_text(face="bold", size=12),axis.text.y = element_text(size=9))+theme(axis.text.x = element_text(angle = 45, hjust = 1))+
    geom_line(linetype="solid", size=1)+geom_point(color="gray7", size=2,shape=15)
msoftrain
  • 1,017
  • 8
  • 23
  • Thank you for your response. I was trying only the as.factor part but the levels that you mentioned, solved my issue. Thank you. Uwe, thank you for the notice. – geo_dd Apr 04 '18 at 16:22