ggplot date scales shifts one month forward

2019-06-22 13:44发布

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.

标签: r date ggplot2
2条回答
ら.Afraid
2楼-- · 2019-06-22 14:04

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

查看更多
Juvenile、少年°
3楼-- · 2019-06-22 14:17

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!

查看更多
登录 后发表回答