I used ggplot2 to draw a trend line based on my data.
Below is something I've done using spreadsheet.
But I only want to show the trend line (black line as shown in upper plot) rather than all dots as number of observation is > 20,000.
So I tried to do the same thing using ggplot2.
fig_a <- ggplot(df1, aes(data_x, data_y ))
fig_a + stat_smooth(method=lm)
fig_a + stat_smooth(method=gam)
Apparently it does not work well, anyone can help?
Why it gives so many lines rather than single trend line?
Adding a regression line on a ggplot You can use geom_smooth() with method = "lm" . This will automatically add a regression line for y ~ x to the plot.
Overview. ggplot2 is a system for declaratively creating graphics, based on The Grammar of Graphics. You provide the data, tell ggplot2 how to map variables to aesthetics, what graphical primitives to use, and it takes care of the details.
Plotting with ggplot2 ggplot2 is a plotting package that provides helpful commands to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties.
You can do the following. Add + geom_smooth(method = "lm")
to your ggplot script.
Example using built-in data
ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = "lm")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With