Search code examples
rdateplotjulian-date

Join year and julian day as a date column in R and plot it


I have some data with a column for the day of the year and another for year. As example, let's think in this dummy data:

temp <- rep(runif(730,15,40))
doy <- rep(c(1:365),2)
year <- c(rep(2015,365), rep(2016,365))

I would like to join doy and year as a date column (2015-365 format). Is it possible to deal with this date format? How ggplot or the basic function plot deal with it?


Solution

  • To convert a Julian date to a Date object use the %j format. For example:

    temp <- rep(runif(730,15,40))
    doy <- rep(c(1:365),2)
    year <- c("2015","2016")
    
    jdate<-as.Date(paste(year, doy, sep="-"),"%Y-%j") 
    df<- data.frame(jdate, temp)
    
    library(ggplot2)
    f<-ggplot(df, aes(x=jdate, y=temp))
    f+ geom_point() + scale_x_date(date_breaks="6 week", date_labels="%Y-%j")