Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make scale_x_date week start with Sunday

Tags:

r

ggplot2

I'm creating a weekly time series chart, and week should start with Sunday. When I specify scale_x_date(breaks = date_breaks('1 week')) grid line and labels start on Monday, so results looks slightly off. How can I force ggplot scale_x_date week to start on Sunday

This is example of my code

library(ggplot2)
library(scales)

data.set <- structure(list(week.start = structure(c(15732, 15739,
                           15746, 15753, 15760, 15767, 15774, 15781,
                           15788, 15795, 15802, 15809 ), class =
                           "Date"), overtime.avg = c(2.8,
                           2.85666666666667, 2.18333333333333,
                           2.44666666666667, 2.04833333333333,
                           2.45833333333333, 2.12833333333333,
                           1.81666666666667, 1.82166666666667,
                           1.54333333333333, 2.09166666666667,
                           0.970833333333333)), .Names =
                           c("week.start", "overtime.avg"), row.names
                           = 29733:29744, class = "data.frame")

ggplot(data = data.set,
       aes(x = week.start,
           y = overtime.avg)) +
    geom_line() +
    geom_point() +
    scale_x_date(breaks = date_breaks("1 week"),
                 labels = date_format(format = "%Y-%m-%d"))
like image 386
ilya Avatar asked Apr 25 '13 14:04

ilya


1 Answers

One way would be to use function seq() and provide your own break points starting with first Sunday (used minimal value of week.start) and set by="week".

ggplot(data = data.set,aes(x = week.start,y = overtime.avg)) +
  geom_line() +
  geom_point() +
  scale_x_date(breaks = seq(min(data.set$week.start),max(data.set$week.start),by="week"),
               labels = date_format(format = "%Y-%m-%d"))
like image 86
Didzis Elferts Avatar answered Sep 28 '22 06:09

Didzis Elferts