我开始在 Excel 中制作日历,但认为在 R 中可能更容易制作。 (注意:我知道各种热图日历包,但我更喜欢使用 ggplot2。)最终我想制作一个日历,显示从给定日期开始的 12 个月,每个月都是一个小月份该框在 y 轴上显示 4 或 5 周(顶部为第 1 周,底部为第 4 或 5 周),沿 x 轴显示一周中的天数(从星期一开始)。
我认为这将是一个 15 分钟的工作(创建所有月份的数据,使用 reshape
进行格式化,然后使用 facet_wrap
),但几乎立即遇到了问题,因为下图显示 - 尽管一周中的日子看起来没问题,但一个月中的日子没有按顺序排列。 R 中的排序数据是我的克星;我确实应该解决这个问题。不管怎样,下图显示了我到目前为止所拥有的内容,代码就在下面。这只是一个有趣的项目,并不紧急,但欢迎任何帮助和/或修饰。
require(ggplot2)
require(scales)
require(lubridate)
date.start <- as.Date('2013-09-01')
date.end <- date.start + months(1)
mydf <- data.frame(mydate = seq(as.Date(date.start),
as.Date(date.end) - days(1),
by = 'day'))
mydf$month <- month(mydf$mydate)
mydf$week <- week(mydf$mydate)
mydf$day <- day(mydf$mydate)
mydf$dow <- as.factor(format(mydf$mydate, format = "%a"))
levels(mydf$dow) <- c('Mon','Tue','Wed','Thu','Fri','Sat','Sun')
ggplot(mydf, aes(x = dow, y = as.factor(week))) +
geom_tile(colour = "black", fill = "white", label = mydf$day) +
geom_text(label = mydf$day, size = 4, colour = "black") +
scale_x_discrete(expand = c(0,0)) +
theme(axis.ticks = element_blank()) +
theme(axis.title.y = element_blank()) +
theme(axis.title.x = element_blank()) +
theme(panel.background = element_rect(fill = "transparent"))+
theme(legend.position = "none") +
theme()
最佳答案
创建 week.f
列,其级别按相反顺序排列。我们使用了 "%U"
(假设美国惯例,但如果您想要英国惯例,请使用 "%W"
并更改 因子水平的顺序道
)。此外,我们还允许任意日期输入来计算月初,并稍微简化了 ggplot 调用。
library(ggplot2)
input <- as.Date("2013-09-11") # input date
st <- as.Date(cut(input, "month")) # calculate start of month
dates31 <- st + 0:30 # st and next 30 dates (31 in all)
dates <- dates31[months(dates31) == months(st)] # keep only dates in st's month
week.ch <- format(dates, "%U") # week numbers
mydf <- data.frame(
day = as.numeric(format(dates, "%d")),
week.f = factor(week.ch, rev(unique(week.ch))),
dow = factor(format(dates, "%a"), c("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"))
)
ggplot(mydf, aes(x = dow, y = week.f)) +
geom_tile(colour = "black", fill = "white") +
geom_text(label = mydf$day, size = 4) +
scale_x_discrete(expand = c(0,0)) +
theme(axis.ticks = element_blank()) +
theme(axis.title = element_blank()) +
theme(panel.background = element_rect(fill = "transparent"))+
theme(legend.position = "none")
顺便说一句,TeachingDemos 包中有一个 cal
函数,可以使用经典图形构建一个月的日历。
关于r - 使用 ggplot2 创建月/年日历图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18741858/