首页 > 解决方案 > 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") +

default

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)) +

expand

Does anyone know how to solve this? I figure the solution is within date_labels or labels... or limits?

标签: rdateggplot2scale

解决方案


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.

working


推荐阅读