【问题标题】:How to smooth the line in R ggplot without using ggalt library如何在不使用 ggalt 库的情况下平滑 R ggplot 中的线条
【发布时间】:2021-12-06 09:25:32
【问题描述】:

我有一个这样的数据框:

df <- data.frame( posting_year = c(2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016), value = c(492, 523, 507, 66, 58, 641, 226, 990, 555, 481) )

这是我使用这段代码得到的折线图:

ggplot(df, aes(x=posting_year , y=value)) + geom_line()

但我想要一个带有曲线的折线图。像这样的

谢谢

【问题讨论】:

标签: r


【解决方案1】:

您可以在此处使用 geom_smooth,但默认情况下您不会得到您想要达到的效果。默认是蓝色的,使用 span 或多或少会产生红色的预期结果。

ggplot(df, aes(x = posting_year, y = value)) + geom_line() + 
  geom_smooth(method = "loess", formula = y ~ x, se = F, span = 0.75, color = "blue") + # default span
  geom_smooth(method = "loess", formula = y ~ x, se = F, span = 0.20, color = "red")

【讨论】:

    【解决方案2】:

    尝试这种接近您想要的方法。你可以定义stat_smooth()

    ggplot(df, aes(x=posting_year , y=value)) +  
      geom_line(color = 'red', size=1)+
      geom_smooth(method = "loess",
                  se = FALSE,
                  formula = 'y ~ x',
                  span = 0.2, 
                  size=1)+
                  theme_bw()
    

    数据:

    df <- data.frame( posting_year = c(2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016), value = c(492, 523, 507, 66, 58, 641, 226, 990, 555, 481) )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-12
      • 2020-08-10
      • 2015-11-16
      • 2013-02-01
      • 2021-02-06
      • 1970-01-01
      • 1970-01-01
      • 2019-11-15
      相关资源
      最近更新 更多