yfuru
yfuru

Reputation: 83

scale_x_date makes plot begins at April, not January in ggplot

I am currently creating a time trend plot in ggplot2. I used scale_x_date() function to create date_breaks of 6 months and have them label at every 6 months, but the graph x-axis begins in April, not January.

library(lubridate)
library(stats)
library(ggplot2)

dates <- seq.Date(mdy("01-01-2013"), mdy("01-01-2017"), by = "month")
value <- rnorm(length(dates))
data <- cbind.data.frame(dates, value)

plot <- ggplot(data, aes(x = dates, y = value)) +
  geom_point() +
  scale_x_date(date_breaks = "6 months",
               date_labels = "%b\n%Y")

The output x-axis begins in April.

enter image description here

I have also tried adding expand = c(0,0):

plot <- ggplot(data, aes(x = dates, y = value)) +
  geom_point() +
  scale_x_date(date_breaks = "6 months",
               date_labels = "%b\n%Y",
               expand = c(0,0))

but it results in: The Jan is right on the x-axis.

Please advise!

Upvotes: 1

Views: 4815

Answers (1)

MLavoie
MLavoie

Reputation: 9886

In your code, there is a mistake between dates and cdates. What about this:

ggplot(data, aes(x = cdates, y = value)) +
   geom_point() +
 scale_x_date(breaks = seq(as.Date("2013-01-01"), as.Date("2017-01-01"), by="6 months"), date_labels = "%b\n%Y")

Upvotes: 9

Related Questions