Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
683 views
in Technique[技术] by (71.8m points)

r - Draw a trend line using ggplot

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...