【问题标题】:Eliminate X-Axis Gaps in ggplot Line Chart消除 ggplot 折线图中的 X 轴间隙
【发布时间】:2020-08-11 09:27:09
【问题描述】:

当我使用 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()

【问题讨论】:

    标签: r dataframe ggplot2 linechart


    【解决方案1】:

    您可以使用任何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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多