Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 577
Sakura Avatar asked Jul 16 '16 15:07

Sakura


People also ask

How do you put a line of best fit on ggplot2?

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.

What does a Ggplot tell you?

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.

How do you describe a Ggplot?

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.


1 Answers

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

like image 53
milan Avatar answered Oct 05 '22 11:10

milan