消除 ggplot 折线图中的 X 轴间隙

Eliminate X-Axis Gaps in ggplot Line Chart

当我用ggplot创建折线图时,x轴的两边出现了两个缺口,如下图所示:

我怎样才能防止这种情况发生,使线条在 x 轴的两个边缘开始和结束,而不仅仅是 before/after?

这是我到目前为止的代码:

germany_yields <- read.csv(file = "Germany 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F)
italy_yields <- read.csv(file = "Italy 10-Year Yield Weekly (2007-2020).csv", stringsAsFactors = F)

germany_yields <- germany_yields[, -(3:6)]
italy_yields <- italy_yields[, -(3:6)]

colnames(germany_yields)[1] <- "Date"
colnames(germany_yields)[2] <- "Germany.Yield"
colnames(italy_yields)[1] <- "Date"
colnames(italy_yields)[2] <- "Italy.Yield"

combined <- join(germany_yields, italy_yields, by = "Date")
combined <- na.omit(combined)
combined$Date <- as.Date(combined$Date,format = "%B %d, %Y")
combined["Spread"] <- combined$Italy.Yield - combined$Germany.Yield

ggplot(data=combined, aes(x = Date, y = Spread)) + geom_line()

您可以使用任何 scale_ ggplot 命令的 expand= 参数来调整比例 limits 和绘图区域边缘之间的缓冲区。

示例:

df <- data.frame(x=1:100, y=rnorm(100))
ggplot(df, aes(x,y)) + geom_line() + xlim(0,100)

x 轴上还有边:

但添加 expand 参数以指定超出 limits 边缘的扩展量。请注意,该参数需要 两个 值,因此您可以指定扩展超过上限和下限的距离:

ggplot(df, aes(x,y)) + geom_line() + scale_x_continuous(limits=c(0,100), expand=c(0,0))