如何去除ggplot绘制的美国GDP趋势图首尾空白区域?
解决GDP趋势折线图首尾空白的问题
你的图表首尾出现空白,主要是因为ggplot默认会给坐标轴添加扩展空间,加上scale_x_yearqtr的参数设置放大了这个问题,单独使用limits无效大概率是因为没有匹配yearqtr类型的边界值。以下是几种有效解决方法:
方法1:关闭坐标轴默认扩展空间
直接在scale_x_yearqtr中添加expand = c(0, 0),彻底移除首尾的空白区域:
scale_x_yearqtr(format = '%Y Q%q', n = 85, expand = c(0, 0))
方法2:精准设置x轴范围(匹配yearqtr类型)
如果需要严格限定数据的时间范围,要确保limits参数的值是yearqtr类型,而不是普通日期或字符串:
scale_x_yearqtr(format = '%Y Q%q', n = 85, limits = c(as.yearqtr("1970 Q1"), as.yearqtr("2022 Q4")), expand = c(0, 0))
方法3:优化刻度数量设置
你当前设置的n=85远超出了合理的刻度密度(1970-2022共208个季度,85个刻度会显得拥挤),可以调小n值,或者手动指定刻度间隔,避免ggplot自动扩展空间:
# 每2年显示一个刻度 scale_x_yearqtr(format = '%Y Q%q', breaks = seq(as.yearqtr("1970 Q1"), as.yearqtr("2022 Q4"), by = 2), expand = c(0, 0))
完整修改后的代码示例
library(ggplot2) library(zoo) library(dplyr) df1 <- df %>% gather(key = "Serie", value = "Value", -date) df1 %>% filter(Serie %in% c("Data", "Trend")) %>% ggplot() + aes(x = as.yearqtr(date), y = exp(Value), colour = Serie) + geom_line(size = 0.75) + scale_color_brewer(palette = "Set1", direction = 1) + labs(x = "Quarter", y = "Billions of USD", title = "UCM - Data and Trend", subtitle = "Guess made with Hodrick and Prescott Filter (1600) and MLE.", caption = "Data obtained from FRED St. Louis") + theme_light() + theme(legend.position = "bottom", plot.title = element_text(size = 20L, face = "bold", hjust = 0.5), plot.subtitle = element_text(size = 15L, hjust = 0.5), axis.text.x = element_text(angle = 90))+ # 结合精准范围与关闭扩展的设置,同时调小刻度数量 scale_x_yearqtr(format = '%Y Q%q', limits = c(as.yearqtr("1970 Q1"), as.yearqtr("2022 Q4")), expand = c(0, 0), n = 20)
内容的提问来源于stack exchange,提问作者Jorge Paredes
相关产品推荐
相关产品推荐

