我有一些假期日期,以及一年中每周的一堆数据。我正在绘制数据并想让 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
labels
和 breaks
, 带有相应的文本标签和您想要的日期。特别是,对于休息时间使用 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/