scale_x_date 中的 limits 参数(ggplot)仍然会产生 data.frame 范围之外的日期

limits argument in scale_x_date (ggplot) still produces dates outside data.frame range

我的 data.frame 看起来像:

df <- data.frame(date=as.Date(c("2017-12-01", "2018-01-01", "2018-02-01")), value=c(1, 2, 3))

并且在使用 ggplot 绘制线条时

library(ggplot2)
ggplot(data=df, aes(x=date, y=value)) +
geom_line() + 
scale_x_date(date_breaks = "day", limits = c(min(df$date), max(df$date))) +
theme(axis.text.x=element_text(angle=90, vjust = 0.5))

给出:

enter image description here

我希望通过在 ggplot 命令中设置限制 (limits = c(min(df$date), max(df$date))),2017 年 11 月和 2018 年 2 月的额外日期会消失,但它们没有。

我真的可以使用scale_x_date将情节限制在“2017-12-01”和“2018-02-01”吗?或者我是否必须放弃日期功能以将两端的绘图限制为我的 data.frame?

中的日期

这很正常,因为您要查找的参数不是 limits,而是 expand,因为这是在限制的左右两侧添加了一点额外的 space。您根本不必指定限制,因为默认情况下使用最小值和最大值。

因此这段代码为您提供了您想要的情节:

ggplot(data=df, aes(x=date, y=value)) +
  geom_line() + 
  scale_x_date(date_breaks = "day", expand = c(0,0)) +
  theme(axis.text.x=element_text(angle=90, vjust = 0.5))

来自帮助页面:

expand : A numeric vector of length two giving multiplicative and additive expansion constants. These constants ensure that the data is placed some distance away from the axes. The defaults are c(0.05, 0) for continuous variables, and c(0, 0.6) for discrete variables.

这给出了