Ggplot date scale moves forward one month

I am sure this is simple, but I could not 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 see, all dates on the X axis are moving forward next month. I tried to use the weight package, as suggested elsewhere, but that did not change anything.

I can get away from this by changing the date using:

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

which provides this (without using a bit scale_x_date):

enter image description here

but I'm sure there is an elegant way around this problem.

+4
source share
2 answers

, dates as.POSIXct scale_x_datetime scale_x_date ( ):

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

+1

, . : "breaks =".

..

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

. "data_breaks" (, ), . "", "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. . , , , , -!

0

Source: https://habr.com/ru/post/1672994/


All Articles