ggplot日期刻度向前移动一个月 [英] ggplot date scales shifts one month forward
问题描述
我确信这很容易,但是我无法从其他帖子中找到解决方案。
I am sure this is an easy one but I couldn't find a solution from other posts.
如果我运行此程序:
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"))
我明白了:
您应该理解,X轴上的所有日期都向前移动到下个月。
我尝试按照其他地方的建议使用 scales 程序包,但并没有改变任何东西。
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"))
可以执行此操作(不使用 scale_x_date
位):
which delivers this (without using the scale_x_date
bit):
但是我敢肯定有一种解决问题的好方法。
but I am sure there is an elegant way to circumvent the problem.
推荐答案
我自己在遇到此问题时做每月的时间序列图。我的解决方案:将日期向量添加到 breaks =部分。
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.
即
scale_x_date(breaks = test$dates, labels = date_format("%b-%y"))
注意:当我尝试使用 data_breaks(例如您的代码)时,我无法使它在一个数字下工作不同的排列。日期向量仅适用于 breaks,不适用于 data_breaks
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"))
Ps这是我在这里回答问题的第一次尝试。我知道这个问题很旧,但是希望这会对某人有所帮助!
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!
这篇关于ggplot日期刻度向前移动一个月的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!