Draw a trend line using ggplot

2020-02-10 05:17发布

问题:

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?

回答1:

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