Search code examples
rgraphggplot2levels

How to plot different months as different series in the same graph in R


I have the following dataset

head(Data)
    Fecha PriceStats
1 01-2002    45.2071
2 02-2002    46.6268
3 03-2002    48.4712
4 04-2002    53.5067
5 05-2002    55.6527
6 06-2002    57.6684

There´s a total of 176 observations.

Every row corresponds to a different month.

I would like to create a graph with the 12 months of the year in the x-axis and that every year of the dataset (containing 12 months each) corresponds to a series in the graph so I can plot all the different years overlapping (in these case would be 15 series).

Do I have to set levels on the dataset or ggplot can do that directly?


Solution

  • This should do it:

    library(ggplot2)
    library(lubridate)
    
    Data <- data.frame(date = seq(ymd('2014/01/01'), ymd('2016/12/01'), 30), 
                           n = sample(1:50, 36))
    
    Data$month <- month(Data$date)
    Data$year <- year(Data$date)
    
    ggplot(Data, aes(x = month, y = n, group = year)) + 
      geom_line(aes(colour = as.factor(year)))