r - 应用假日标签按一年中的一周绘制

标签 r ggplot2

我有一些假期日期,以及一年中每周的一堆数据。我正在绘制数据并想让 X 轴标签仅在我的假期表中有假期时显示。其余的标签应该隐藏。我想我需要的是一个列表,其中名称是一年中的第几周,值是我想要的字符串,但我不知道如何以编程方式生成它。

library(tidyverse)
library(lubridate)

holiday_dates = c(
  "2016-01-01",
  '2016-01-18',
  '2016-02-15',
  '2016-05-08',
  '2016-05-30',
  '2016-06-19',
  '2016-07-04',
  '2016-09-16',
  '2016-10-10',
  '2016-11-11',
  '2016-11-24',
  '2016-12-25'
)
holiday_names = c(
  'New Years Day',
  'Martin Luther King Day',
  'Presidents Day',
  'Mothers Day',
  'Memorial Day',
  'Fathers Day',
  'Independence Day',
  'Labor Day',
  'Columbus Day',
  'Veterans Day',
  'Thanksgiving',
  'Christmas Day'
)
holidays = data.frame(Date = as.Date(holiday_dates), Holiday = holiday_names) %>%
  mutate(WeekOfYear = week(Date))

# can't figure out how to make this a list with names generates from the WeekOfYear column
holiday_labels = data.frame(WeekOfYear = seq(1,52)) %>% 
  left_join(holidays) %>% 
  .$Holiday

my_data %>%
  ggplot(aes(x=WeekOfYear, y=Gross, group=WeekOfYear)) +
  geom_line() +
  scale_x_discrete(
    names = holiday_labels,
    na.value = ""
  )

最佳答案

  • 使用 scale_x_continuous而不是 scale_x_discrete
  • 设置两者 labelsbreaks , 带有相应的文本标签和您想要的日期。特别是,对于休息时间使用 week(as.Date(holiday_dates))将其放在与您的数据相同的规模上。

  • 例如:
    data_frame(WeekOfYear = 1:52, Gross = rnorm(52)) %>%
      ggplot(aes(x = WeekOfYear, y = Gross)) +
      geom_line() +
      scale_x_continuous(
        labels = holiday_names,
        breaks = week(as.Date(holiday_dates))
      ) +
      theme(axis.text.x = element_text(angle = 90, hjust = 1))
    



    请注意,我还旋转了 x 轴标签以使其可读。

    关于r - 应用假日标签按一年中的一周绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39937090/

    相关文章:

    r - 如何使用 RSQLite 从数据库中检索大量数据? (缓冲区溢出?)

    从字符串中删除相邻的重复项

    r - ggplot2 和 ggdendro - 在节点叶子下绘制颜色条

    r - float 条形图

    python - 将逻辑回归从 R 迁移到 rpy2

    r - 将逻辑运算符与 %in% 和子集一起使用

    R - 使用 ggplot 在同一图表上为三个数据集创建图例

    r - 时间序列图矩阵

    r - ggplot2 的组合图(不在单个图中),使用 par() 或 layout() 函数?

    r - 如何在一个ggplot中有两个不同大小的图例?