Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot date scales shifts one month forward

Tags:

date

r

ggplot2

I am sure this is an easy one but I couldn't find a solution from other posts.

If I run this:

test <- data.frame(dates = as.Date(c("2016-10-31","2016-11-30", "2016-12-31", "2017-01-31")), 
                   values = c(1, 2, 3, 4))
ggplot(test, aes(x = dates, y = values)) +
  geom_bar(position="stack", stat = "identity") + 
  scale_x_date(breaks = date_breaks("1 months"),labels = date_format("%b-%y"))

I get this:

enter image description here

As you can appreciate, all the dates on the X axis are moved forward to the following month. I tried to use the scales package as suggested elsewhere but it didn't change a thing.

I can get away with this by tweaking the date using:

test$dates <- as.Date(format(test$dates, "%Y-%m-1"))

which delivers this (without using the scale_x_date bit):

enter image description here

but I am sure there is an elegant way to circumvent the problem.

like image 341
Matteo Castagna Avatar asked Mar 23 '17 10:03

Matteo Castagna


2 Answers

I have run into this problem myself when doing monthly time series charts. My solution: add in a vector of dates into the "breaks = " section.

I.e.

scale_x_date(breaks = test$dates, labels = date_format("%b-%y"))

Note: When I tried "data_breaks" (like your code), I was not able to get it to work under a number of different permutations. The vector of dates only works with "breaks", not "data_breaks"

  ggplot(test, aes(x = dates, y = values)) +
      geom_bar(position="stack", stat = "identity") + 
      scale_x_date(breaks = test$dates, labels = date_format("%b-%y"))

P.s. This is my first attempt at answering a question here. I know that the question is old, but hopefully this will help someone!

like image 123
Piranha Avatar answered Oct 24 '22 08:10

Piranha


The labels are correct when you transform dates with as.POSIXct and use scale_x_datetime instead of scale_x_date (no idea why though):

ggplot(test, aes(x = as.POSIXct(dates), y = values)) +
  geom_bar(position="stack", stat = "identity") + 
  scale_x_datetime(breaks = date_breaks("1 months"), labels = date_format("%b-%y"))

enter image description here

like image 2
erc Avatar answered Oct 24 '22 09:10

erc