How can I order the months chronologically in ggplot2 short of writing the months out?

后端 未结 1 561
盖世英雄少女心
盖世英雄少女心 2020-11-30 06:26

I am trying to plot count v/s month

ggplot(dat, aes(x=month, y=count,group=region)) +
    geom_line(data=mcount[mcount$region == \"West coast\", ],colour=\"b         


        
相关标签:
1条回答
  • 2020-11-30 06:36

    Use the built-in month.name or month.abb variable to specify the levels of your factor in the correct order. In this case, you have abbreviations so month.abb is appropriate.

    your_data$month = factor(your_data$month, levels = month.abb)
    

    I think creating the factor in the correct order is the best way, but you can also just order the axis using the limits argument of the discrete scale (see ?discrete_scale for more info).

    + scale_x_discrete(limits = month.abb)
    

    Edit: If you are in a non-English locale, you can construct your own month name constants with a little date formatting (basically stolen from Brian Ripley in this R-Help thread):

     month.name.loc = format(ISOdate(2004, 1:12, 1), "%B")
     month.abb.loc  = format(ISOdate(2004, 1:12, 1), "%b")
    
    0 讨论(0)
提交回复
热议问题