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:
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):
but I am sure there is an elegant way to circumvent the problem.
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!
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With