You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R ggplot绘制厄瓜多尔GDP折线图如何实现2022年起实线转虚线

实现方案

你可以通过两次调用geom_line分别绘制实际值和预测值两段线条,这种方式操作简单,还能保证两段线条无缝衔接:

library(tidyverse)

forecast %>%
  filter(Year >= 2015L & Year <= 2026L) %>%
  ggplot(aes(x = Year, y = `Real GDP Growth`)) +
  # 绘制2015-2021年实际值实线
  geom_line(data = ~filter(.x, Year <= 2021), size = 0.75, colour = "#B22222", linetype = "solid") +
  # 绘制2021-2026年预测值虚线,包含2021年数据避免线条断裂
  geom_line(data = ~filter(.x, Year >= 2021), size = 0.75, colour = "#B22222", linetype = "dashed") +
  labs(x = "年份", y = "GDP增速", title = "厄瓜多尔实际GDP增速预测", subtitle = "数据来自世界经济展望") +
  theme_light() +
  theme(
    plot.title = element_text(size = 18L, face = "bold", hjust = 0.5),
    plot.subtitle = element_text(size = 13L, hjust = 0.5),
    axis.title.y = element_text(size = 13L, face = "bold"),
    axis.title.x = element_text(size = 13L, face = "bold"),
    # 不需要图例的话可加上下方代码
    # legend.position = "none"
  ) +
  scale_x_continuous(n.breaks = 11) +
  geom_hline(yintercept = 0, lty = 5, size = 0.75)

如果需要通过字段映射统一管理线型,可以先新增标记字段再映射到linetype参数:

forecast %>%
  filter(Year >= 2015L & Year <= 2026L) %>%
  mutate(数据类型 = ifelse(Year <= 2021, "实际值", "预测值")) %>%
  ggplot(aes(x = Year, y = `Real GDP Growth`)) +
  geom_line(aes(linetype = 数据类型), size = 0.75, colour = "#B22222") +
  scale_linetype_manual(values = c("实际值" = "solid", "预测值" = "dashed")) +
  # 后续 labs、theme 等配置和上述代码一致

内容的提问来源于stack exchange,提问作者Jorge Paredes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:45:03