Home > Mobile >  How to smooth the line in R ggplot without using ggalt library
How to smooth the line in R ggplot without using ggalt library

Time:12-07

I have a data frame like this:

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) )

This is the line chart I get using this code:

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

enter image description here

But I want a line chart with a curve line. Something like this

enter image description here

Thank you

CodePudding user response:

You can use geom_smooth here, but default you get not what you try to achieve. Default is the blue one, playing around with span gives more or less the desired result in red.

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")

enter image description here

CodePudding user response:

Try this approach that is close to what you want. You can define 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()

Data:

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) )

enter image description here

  •  Tags:  
  • r
  • Related