如何在ggplot2中将一条线从实线过渡到点线

Posted

技术标签:

【中文标题】如何在ggplot2中将一条线从实线过渡到点线【英文标题】:How to transition a line from solid to dotted in ggplot2 【发布时间】:2021-12-07 16:04:36 【问题描述】:

我得到了以下关于厄瓜多尔 GDP 增长和 IMF 预测的数据。

我想做一个图表,从 2015 年到 2021 年是一条线 (geom_line),但从 2022 年到 2026 年是一条虚线,我希望这表明从 2022 年开始是预测。

这是我的代码,但我不知道如何陈述条件。

forecast %>%
 filter(Year >= 2015L & Year <= 2026L) %>%
 ggplot() +
 aes(x = Year, y = `Real GDP Growth`) +
 geom_line(size = 0.75, colour = "#B22222") +
 labs(x = "Year", y = "GDP Growth", title = "Ecuador's Real GDP growth Forecast", subtitle = "Forecast done by the World Economic Outlook") +
 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"))+scale_x_continuous(n.breaks=11)+geom_hline(yintercept = 0, lty=5, size=0.75)


这是数据:

structure(list(Year = c(1980, 1981, 1982, 1983, 1984, 1985, 1986, 
1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 
1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 
2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 
2020, 2021, 2022, 2023, 2024, 2025, 2026), `Real GDP Growth` = c(4.9, 
3.9, 1.2, -2.8, 4.2, 4.4, 3.1, -6, 10.5, 0.3, 3, 5.1, 3.6, 2, 
4.3, 2.3, 1.7, 4.3, 3.3, -4.7, 1.1, 4, 4.1, 2.7, 8.2, 5.3, 4.4, 
2.2, 6.4, 0.6, 3.5, 7.9, 5.6, 4.9, 3.8, 0.1, -1.2, 2.4, 1.3, 
0, -7.8, 2.8, 3.5, 2.5, 2.6, 2.8, 2.8)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = c(NA, -47L))

最终的图表应如下所示:

提前感谢所有帮助。

【问题讨论】:

谢谢,我会解决的 【参考方案1】:

试一试 - 我将您的数据分成两组,用于两种线型,并对其余部分进行了一些重组和简化:

ggplot() +
  aes(x = Year, y = `Real GDP Growth`) +
  geom_line(data = filter(forecast, Year <= 2021), size = 0.75, colour = "#B22222") +
  geom_line(data = filter(forecast, Year >= 2021), size = 0.75, colour = "#B22222", linetype = "dotted") +
  labs(
    x = "Year", y = "GDP Growth", 
    title = "Ecuador's Real GDP growth Forecast", 
    subtitle = "Forecast done by the World Economic Outlook") +
  scale_x_continuous(n.breaks = 11) + 
  geom_hline(yintercept = 0, lty = 5, size = 0.75) +
  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 = element_text(size = 13L, face = "bold")
  ) 

【讨论】:

是的!这正是我所需要的,谢谢!

以上是关于如何在ggplot2中将一条线从实线过渡到点线的主要内容,如果未能解决你的问题,请参考以下文章

图例在 ggplot2 密度图中不显示线型

我们可以在R(ggplot2)中为(虚线)线添加阴影吗?

周MACD线显示在日图时如何变色?

如何在python中绘制一条线,每个数据点都有一个间隔

R geom_hline 只显示实线

如何在辅助 y 上用一条线和另一条线创建面积图