消除ggplot线图中的X轴间隙

问题描述 投票:0回答:1

当我使用ggplot创建折线图时,x轴的两侧会出现两个间隙,如下所示:

enter image description here

如何防止这种情况,使线条在x轴的两个边缘开始和结束,而不是仅仅在之前/之后?

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

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()
r dataframe ggplot2 linechart
1个回答
0
投票

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

示例:

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

您仍然在x轴上有边缘:

enter image description here

但是添加expand参数以指定要扩展到limits边缘之外的范围。请注意,该参数需要two值,因此您可以指定扩展超出上限和下限的距离:

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

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.