您可以使用ggplot2 和scales 来实现:
library(gglot2)
library(scales)
首先创建一个带有data = D 和time 的ggplot 作为你的x 审美。添加geom_bar()(即条形图)并更改 x 轴以仅显示月份并设置特定限制(在本例中为 2007 年的第一天和最后一天):
ggplot(data = D, aes(x = time)) + geom_bar() +
scale_x_date(labels = date_format("%b"),
limits = c(as.Date('2007-01-01'), as.Date('2007-12-31')))
返回:
如果您想显示每月的事件,您可以使用lubridate 和dplyr 和ggplot2:
library(dplyr)
library(lubridate)
library(ggplot2)
D = data.frame(time = c("2007-06-22","2007-05-22","2007-05-23"))
在这种情况下,您会得到日期的缩写月份:
D2 <- D
D2$month <- month(D$time, label = TRUE)
您可以按月分组并统计事件数:
D2 <- D2 %>%
group_by(month) %>%
summarise(n = n())
使用n = 0 将缺少的月份(如果有)添加到您的数据框中:
D2 <- rbind(D2,
data.frame(month = levels(D2$month)[!(levels(D2$month) %in% D2$month)],
n = 0))
绘制新数据(注意:在geom_bar() 中使用stat = 'identity',因为您在y 美学中明确传递了计数:):
ggplot(data = D2, aes(x = month, y = n)) +
geom_bar(stat = 'identity')
返回:
选项编号 3:
使用多年的更灵活的方法:
D = data.frame(time = c("2006-05-16", "2007-06-22","2007-05-22","2007-05-23"))
(注:添加不同年份的一个日期)
创建一个额外的year 列:
D3 <- D
D3$month <- month(D$time, label = TRUE)
D3$year <- year(D$time)
按month 和year 分组:
D3 <- D3 %>%
group_by(year, month) %>%
summarise(n = n())
找出每年缺失的月份:
missing <- do.call("rbind",
lapply(unique(D3$year), function(y) {
data.frame(year = y,
month = levels(D3[D3$year == y, ]$month)[!(levels(D3[D3$year == y, ]$month) %in% D3[D3$year == y, ]$month)],
n = 0)
}))
结合D3和missing:
all <- rbind(as.data.frame(D3), missing)
创建新的可视化:
ggplot(data = all, aes(x = month, y = n, group = factor(year), fill = factor(year))) +
geom_bar(position = "dodge", stat = 'identity')
看起来像这样: