r - ggplot: scale date monthly from Jan:Dec not Jan:Jan or Feb:Jan
问题描述
I have as.Date() (daily) data which I'm plotting with monthly labels, but I can't work out how to force it to format 'nicely':
1: default, includes additional terminal Jan at the top, which labels no data.
scale_y_date(date_breaks = "1 month", date_labels = "%b") +
2: Use of expand removes additional whitespace (good) and removes a Jan label (good) but it removes the first one not the last one (bad).
scale_y_date(date_breaks = "1 month", date_labels = "%b", expand = c(0, 0)) +
Does anyone know how to solve this? I figure the solution is within date_labels
or labels
... or limits
?
解决方案
Turns out it was in limits
, but am now puzzled as to how the limits I set are different from the default. Did some digging. My y data are:
y = as.Date(Day, origin = as.Date("2018-01-01"))
The range()
of this is
"2018-01-02" "2019-01-02"
The range()
of my 'Day' variable is
1 366
So evidently R/ggplot is counting yeardays from 0. If I subtract 1:
y = as.Date(Day - 1, origin = as.Date("2018-01-01"))
The max value is now "2019-01-01" which therefore adds the duplicate January, presumably due to leap year days adding to 366. This can be solved in the data by subtracting 1 to the entire series and using (e.g.) case_when
to convert 365s to 364s, or in ggplot:
scale_y_date(date_breaks = "1 month", date_labels = "%b", expand = c(0, 0), limits = c(as.Date("2018-01-01"), as.Date("2018-12-31"))) +
Surprisingly annoying, but hopefully this helps someone else having this issue.
推荐阅读
- reactjs - webpack 构建没有路由组件的网站
- google-bigquery - 使用 Batch 对象时云函数停止执行
- python-3.x - IndexError:列表索引超出范围 sys.argv[2]
- javascript - 如何停止/暂停 d3 中的特定力?
- c# - 必须声明标量变量“@GenName”
- python - python中的递归搜索
- javascript - 为什么我的圈子不动,代码似乎正确
- python - 如何使用python超类和继承(海龟图形示例)?
- angularjs - 通过 grunt webpack 运行的 Webpack 不会出错或完成,或做任何事情
- dart - Flutter中如何实现动态widget路由?