当我使用ggplot创建折线图时,x轴的两侧会出现两个间隙,如下所示:
如何防止这种情况发生,以使直线在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()
答案 0 :(得分:1)
您可以使用任何expand=
ggplot命令中的scale_
参数来调整刻度尺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))