R语言 在ggplot2中为一组月份分组年份时创建月日标签

camsedfj  于 2023-11-14  发布在  其他
关注(0)|答案(1)|浏览(132)

下面是示例代码。我想做的是取一个系列,并比较不同年份在一组月份(9月到11月)的值。然而,我在创建标签时遇到了问题,因为在我将日期格式化为月-日之后,该列不再是日期。
对于标签,我想每隔n天做一次,并让它们以类似于第二个图的方式显示,月份缩写,日期作为月份的编号。

date = seq(dmy("01-01-2020"), dmy("01-01-2023"), by = "day")
sample = rnorm(length(date), mean = 0, sd = 0.2)
tb <- tibble(date = date, sample = sample)
tb %>%
  filter(month(date) >= 09, month(date) <= 11) %>%
  mutate(year = year(date), day = factor(format(as_date(date), "%m-%d"))) %>%
  ggplot(aes(x = day, y = sample, group = factor(year),color = factor(year))) + 
  geom_line(size = 0.75)

### The way I would like the labels to look

tb %>%
  ggplot(aes(x = date, y = sample)) +
  geom_line() +
  scale_x_date(breaks = seq(as.Date("2016-01-01"), as.Date("2024-01-01"), by="6 months"), date_labels = "%b\n%Y")

字符串
我还注意到,当我使用day = factor(format(as_date(date), "%m-%d"))而不是day = factor(format(as_date(date), "%b-%d"))时,图形会发生变化
我不知道为什么。

lp0sw83n

lp0sw83n1#

一种选择是创建一个带有固定年份的假日期列:

library(tidyverse)

set.seed(123)

date <- seq(dmy("01-01-2020"), dmy("01-01-2023"), by = "day")
sample <- rnorm(length(date), mean = 0, sd = 0.2)
tb <- tibble(date = date, sample = sample)

# Create fake date with fixed year
tb$date1 <- tb$date
year(tb$date1) <- 2020

tb %>%
  filter(month(date) >= 09, month(date) <= 11) %>%
  mutate(year = year(date)) %>%
  ggplot(aes(
    x = date1, y = sample, group = factor(year),
    color = factor(year)
  )) +
  geom_line(size = 0.75) +
  scale_x_date(
    date_labels = "%b\n%d"
  )

字符串


的数据

相关问题