Search code examples
rggplot2time-serieslinegraphtimeserieschart

ggplot2: How to change position of tick/grid lines to align with dates in data


I am trying to plot some data where my x-axis is date. Please see the sample data below.

Test.Data <- data.frame(weekBeginDate = c("2017-10-21", "2017-10-28", "2017-11-04", "2017-11-11", "2017-11-18", "2017-11-25", "2017-12-02", "2017-12-09", "2017-12-16", "2017-12-23", "2017-12-30"), Temperature = sample(1:11))

When I plot this data using ggplot using the following code, I get the below output.

Test.Data$weekBeginDate <- as.Date(Test.Data$weekBeginDate)
Test.Data.plot <- ggplot(Test.Data, aes(x = weekBeginDate,y = WeeklyAvg)) + 
    geom_line(aes(y = Temperature), size=1.25) + 
    labs(y = "Air Temperature [°C]", x = "Date") +
    scale_x_date(date_breaks = "4 weeks", date_minor_breaks = "weeks") +
    theme(axis.text.x = element_text(angle = 45, hjust = 1))

ggplot graph showing time series of sample temperature data

As you can see, the tick or grid lines on the graph don't align with the dates that were used in the data (e.g., the labeled dates on the graph are 2017-11-13 and 2017-12-11, whereas I would like them to be 2017-11-11 and 2017-12-09, for example). Is there a way to change the date on which the grid lines appear?

Much thanks in advance!


Solution

  • Set breaks in scale_x_date to your desired x values, which in this case is the whole vector of dates in Test.Data$weekBeginDate:

    ggplot(Test.Data, aes(x = weekBeginDate,y = WeeklyAvg)) + 
        geom_line(aes(y = Temperature), size=1.25) + 
        labs(y = "Air Temperature [°C]", x = "Date") +
        scale_x_date(breaks = Test.Data$weekBeginDate) +
        theme(axis.text.x = element_text(angle = 45, hjust = 1))
    

    enter image description here