我试图了解ggplot2如何处理scale_x_date()中的break和minor_breaks。
这是一个包含月度数据的简单时间序列:
months <- as.Date(seq(as.Date('2014-09-01'), as.Date('2015-08-01'), by = "1 month"))
values <- sample(1:50, length(months), replace=T)
df <- data.frame(months, values)
我是出于审美原因手动设置限制:
library(lubridate)
my_limits <- c(floor_date(min(df$dates), "year"), ceiling_date(max(df$dates), "year")) # 2014-01-01, 2015-01-01
情节1未发生错位:
library(ggplot2)
library(scales)
p1 <- ggplot(data = df, aes(x = dates, y = values))
p1 <- p1 + geom_line()
p1 <- p1 + scale_x_date(limits = my_limits, breaks = pretty_breaks(), minor_breaks = date_breaks("3 months"))
p1
图2与图1相同(也有未对齐的小间断):
p2 <- ggplot(data = df, aes(x = dates, y = values))
p2 <- p2 + geom_line()
p2 <- p2 + scale_x_date(limits = my_limits, breaks = date_breaks("1 year"), minor_breaks = date_breaks("3 months"))
p2
Plot 3有一些奇怪的标签(我预计2014-01-01和2015-01-01):
p3 <- ggplot(data = df, aes(x = dates, y = values))
p3 <- p3 + geom_line()
p3 <- p3 + scale_x_date(limits = my_limits, breaks = date_breaks("12 months"), minor_breaks = date_breaks("3 months"))
p3
我有两个问题:为什么(有什么好处)?有没有办法让休息时间和未成年人匹配一年的开始?
答案 0 :(得分:3)
看起来像添加expand = c(0,0)有帮助。
情节4:
p4 <- ggplot(data = df, aes(x = dates, y = values))
p4 <- p4 + geom_line()
p4 <- p4 + scale_x_date(expand = c(0, 0), limits = my_limits, breaks = date_breaks("12 months"), minor_breaks = date_breaks("3 months"))
p4