【发布时间】:2020-02-19 00:59:49
【问题描述】:
以下是一家公司按两个同类群组划分的净收入示例数据:
data <- data.frame(dates = rep(seq(as.Date("2000/1/1"), by = "month", length.out = 48), each = 2),
revenue = rep(seq(10000, by = 1000, length.out = 48), each = 2) * rnorm(96, mean = 1, sd = 0.1),
cohort = c("Group 1", "Group 2"))
我可以显示一年的数据,它会返回我期望的结果:
start = "2000-01-01"
end = "2000-12-01"
ggplot(data, aes(fill = cohort, x = dates, y = revenue)) +
geom_bar(stat = "identity", position = position_dodge(width = NULL)) +
xlab("Month") +
ylab("Net Revenue") +
geom_text(aes(label = round(revenue, 0)), vjust = -0.5, size = 3, position = position_dodge(width = 25)) +
scale_x_date(date_breaks = "1 month", limits = as.Date(c(start, end))) +
ggtitle("Monthly Revenue by Group") +
theme_minimal() +
theme(axis.text.x = element_text(angle = 60, hjust = 1), plot.title = element_text(hjust = 0.5)) +
scale_fill_manual(values=c("#00BFC4", "#F8766D"))
但如果我将日期范围扩大到两年或更长时间并重新运行图表,它会在 x 轴两侧显示额外的月份,尽管在 y 轴上没有显示任何信息。
start = "2000-01-01"
end = "2001-12-01"
#rerun the ggplot code from above
请注意 1999-12-01 和 2002-01-01 的不存在数据点。为什么会出现这些以及如何删除它们?
【问题讨论】: