Warm tip: This article is reproduced from stackoverflow.com, please click
dataframe ggplot2 linechart r

Eliminate X-Axis Gaps in ggplot Line Chart

发布于 2020-07-20 16:06:03

When I create a line chart with ggplot, two gaps appear on either side of the x-axis, as can be seen below:

enter image description here

How can I prevent this so that the line starts and ends at both edges of the x-axis, rather than just before/after?

Here is the code I far so far:

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()
Questioner
Ryan Walter
Viewed
6
chemdork123 2020-04-28 02:24

You can use the expand= argument from any scale_ ggplot command to adjust the buffer between the limits of the scale and the edge of the plot area.

Example:

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

You still have the edges on the x axis:

enter image description here

But add the expand argument to specify how much to expand past the edges of the limits. Note that the argument expects two values, so you can specify how far to expand past the upper and lower limits:

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

enter image description here