我有一些假期日期,以及一年中的一堆数据。我正在绘制数据并希望只在假期表中有假期时才显示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 = ""
)
答案 0 :(得分:8)
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轴标签以使其可读。