1

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!

yfuru
  • 73
  • 1
  • 7
  • 3
    please provide a reproducible example. – MLavoie Feb 23 '18 at 01:23
  • when someone ask for reproducible example it means for a sample data and the code you are using so the error can be reproduce, this way its impossible to get the same problem you are facing – Alejandro Andrade Feb 23 '18 at 02:07
  • Welcome to StackOverflow. In order to ask a better question please read [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and [Minimal, Complete, and Verifiable Example](https://stackoverflow.com/help/mcve) and [How to make a great R reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Rui Barradas Feb 23 '18 at 11:03
  • 1
    @MLavoie here is an example. – yfuru Feb 23 '18 at 14:39
  • @AlejandroAndrade here is an example! – yfuru Feb 23 '18 at 14:40
  • @RuiBarradas I apologize. This was my first ever post. – yfuru Feb 23 '18 at 14:40

1 Answers1

8

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")
MLavoie
  • 9,671
  • 41
  • 36
  • 56
  • I apologize. That 'c' in 'cdates' must have been a typo from the post. The results are fixed! – yfuru Feb 23 '18 at 15:15