Draw a trend line using ggplot

Sakura picture Sakura · Jul 16, 2016 · Viewed 92k times · Source

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?

Answer

milan picture milan · Jul 16, 2016

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

enter image description here