26

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?

Sakura
  • 699
  • 1
  • 9
  • 14

1 Answers1

52

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

milan
  • 4,782
  • 2
  • 21
  • 39
  • ggplot(mpg, aes(displ, hwy)) + geom_point() + geom_smooth(method = "lm") it does not work. many lines appeared as well. – Sakura Jul 16 '16 at 16:01
  • 1
    Could you try to insert your variables in the line of code shown above? – milan Jul 16 '16 at 16:04
  • The code works fine here. Maybe try to re-install the library for ggplot2; otherwise, you could update your version of R (if not using the most recent). Not sure, but could work. – milan Jul 16 '16 at 16:30
  • right, probably because I have > 20,000 data point, I do not know, but I am using updated version. Thank you. – Sakura Jul 16 '16 at 16:33
  • 3
    @Sakura: I confirm that milan's code is working for me. Just a little tip, if you "only want to show the trend line" (as you asked), omit geom_point() in milan's code. Thus resulting in ggplot(mpg, aes(displ, hwy)) + geom_smooth(method = "lm") – Eugen Jul 16 '16 at 18:49
  • @milan Thanks for your help, but sorry the code does not work on my case, I do not know why, so would you mind I delete my question? Before this, would you mind deleting the answer, please? – Sakura Jul 16 '16 at 19:01