Search code examples
rggplot2posixctjulian-date

Converting POSIXct to Julian Dates in ggplot


I have been trying to convert POSIXct format so that my date and times would reflect Julian dates.

ind$DateAndTime <- as.POSIXct(ind$DateAndTime, tz = "UTC",
                                  origin = '1970-01-01')

ind$DateAndTime<- format(as.POSIXct(ind_steps$t2),"%y%j")

I had used these two lines of code to do so, but I am now having trouble plotting them using ggplot.

    plot_list[[i]]  <- ggplot(ind, aes(x = DateAndTime, y = NSD)) + 
      geom_line() + theme_bw() +
      ggtitle(random_tables[i]) +
      theme(axis.text.x = element_text(angle = 90))

When I plot it I get this, where the julian dates are vertical, but they still overlap. I would like to get the graph to show the julian dates more visibly and to show every other julian date so that it isn't so cramped in the x-axis. Is there a way to do this?

enter image description here


Solution

  • Here is the completed code. Without any sample data, it is difficult to provide an exact example.

    From your previous question, your issue maybe related to attempting to pass a datetime object to a function expecting a date object. In this case I used as.Date() and scale_x_date(), in your case you may want to use as.POSIXct() and scale_x_datetime()

    #create dummy data
    DateAndTime = 18000:18300
    NSD = DateAndTime/10000
    ind <-data.frame(DateAndTime, NSD)
    
    #convert the DateAndTime column into a date object
    ind$DateAndTime <- as.Date(ind$DateAndTime, tz = "UTC",
                                  origin = '1970-01-01')
    
    #Plot table and format x-axis
    ggplot(ind, aes(x = DateAndTime, y = NSD)) + 
       geom_line() + theme_bw() +
       ggtitle("Demo Title") +
       scale_x_date(date_breaks = "1 month", date_labels = "%y-%j")
       theme(axis.text.x = element_text(angle = 90))