[R] How to add a geom_smooth() line

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Fri Aug 24 06:14:13 CEST 2018


Sorry, should be geom_smooth, not stat_smooth. They both work the same 
way or very close to it.

Rui Barradas

On 24/08/2018 05:08, Rui Barradas wrote:
> Hello,
> 
> The trick is to reshape your data from wide to long format.
> There are many ways to do this, I will use package reshape2.
> 
> Make up a dataset:
> 
> 
> library(ggplot2)
> library(reshape2)
> 
> set.seed(9773)
> n <- 20
> data <- data.frame(timeline = 1:n,
>                     deliveries = log(1:n) + runif(n),
>                     launches = (1:n)/4 + runif(n))
> 
> # reformat it
> long <- melt(data, id.vars = "timeline")
> head(long)
> 
> # et voila!
> ggplot(long, aes(timeline, value, colour = variable)) +
>      geom_point() +
>      stat_smooth() +
>      xlab("Deliveries") +
>      ylab("Launches") +
>      ggtitle("Scatterplot of Launches vs. Deliveries")
> 
> 
> Use the smoothing function of your choice, I left it with the default 
> loess.
> 
> Hope this helps,
> 
> Rui Barradas
> 
> 
> On 24/08/2018 03:38, Jeff Reichman wrote:
>> R-help
>>
>>
>> I want to add two smooth lines (geom_smooth()) for each scatter plot.  
>> How
>> do I do that?
>>
>>
>> ggplot() +
>>
>>    geom_point(data=data, aes(x=timeline, y=deliveries), color="blue") +
>>
>>    geom_point(data=data, aes(x=timeline, y=launches), color="red") +
>>
>>    xlab("Deliveries") +
>>
>>    ylab("Launches") +
>>
>>    ggtitle("Scatterplot of Launches vs. Deliveries")
>>
>>
>> Jeff
>>
>>
>>     [[alternative HTML version deleted]]
>>
>> ______________________________________________
>> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide 
>> http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
>>
> 
> ---
> This email has been checked for viruses by AVG.
> https://www.avg.com
> 
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide 
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list