user2955884
user2955884

Reputation: 551

ggplot: conflict between date_breaks() and limits

I want to get the dates in the x axis every 3 months and thus use date_breaks("3 month"), but the periods start on 1/03 and want them to go 1/1, 1/4 etc. This is what I try:

datos <- data.frame(fecha= date_decimal(seq(2013.0,2013.99,by=0.01)),val=runif(100,1,2))
fini <- ymd("20130101")
ffin <- ymd("20131231")
ggplot(data=datos) + geom_point(aes(x=fecha,y=val)) +
  scale_x_datetime(breaks = date_breaks("3 month"),
                   limits=c(fini,ffin),
                   labels = date_format("%d-%m-%Y"))

Also tried:

ggplot(data=datos) + geom_point(aes(x=fecha,y=val)) +
scale_x_datetime(breaks = date_breaks("3 month"),
                 labels = date_format("%d-%m-%Y")) +
xlim(c(fini,ffin))

but then get the months with acronyms and need numbers (looks like the xlim() cancels the previous scale_x_datetime() )

Upvotes: 3

Views: 863

Answers (1)

JasonAizkalns
JasonAizkalns

Reputation: 20463

This should work:

library(ggplot2)
library(scales)
library(lubridate)
datos <- data.frame(fecha= date_decimal(seq(2013.0,2013.99,by=0.01)),val=runif(100,1,2))
fini <- ymd("20130101")
ffin <- ymd("20140101")

datebreaks <- seq(as.Date(fini), as.Date(ffin), by="3 month")

ggplot(data=datos) + 
  geom_point(aes(x = as.Date(fecha), y = val)) +
  scale_x_date(breaks = datebreaks,
               limits = c(as.Date(fini), as.Date(ffin)),
               labels = date_format('%d-%m-%Y')) 

Upvotes: 3

Related Questions