Skip to content

geom_smooth

5 messages · Thomas Subia, Rui Barradas, Berwin A Turlach +1 more

#
Colleagues,

Here is my reproducible code for a graph using geom_smooth
set.seed(55)
scatter_data <- tibble(x_var = runif(100, min = 0, max = 25)
?????????????????????? ,y_var = log2(x_var) + rnorm(100))

library(ggplot2)
library(cowplot)

ggplot(scatter_data,aes(x=x_var,y=y_var))+
? geom_point()+
? geom_smooth(se=TRUE,fill="blue",color="black",linetype="dashed")+
? theme_cowplot()

I'd like to add a black boundary around the shaded area. I suspect this can be done with geom_ribbon but I cannot figure this out. Some advice would be welcome.

Thanks!

Thomas Subia
#
?s 05:17 de 12/08/2023, Thomas Subia via R-help escreveu:
Hello,

Here is a solution. You ,ust access the computed variables, which you 
can with ?ggplot_build.
Then pass them in the data argument.



p <- ggplot(scatter_data,aes(x=x_var,y=y_var)) +
   geom_point()+
   geom_smooth(se=TRUE,fill="blue",color="black",linetype="dashed")+
   theme_cowplot()

# this is a data.frame, relevant columns are x,  ymin and ymax
fit <- ggplot_build(p)$data[[2]]

p +
   geom_line(data = fit, aes(x, ymin), linetype = "dashed", linewidth = 1) +
   geom_line(data = fit, aes(x, ymax), linetype = "dashed", linewidth = 1)


Hope this helps,

Rui Barradas
#
G'day Thomas,

On Sat, 12 Aug 2023 04:17:42 +0000 (UTC)
Thomas Subia via R-help <r-help at r-project.org> wrote:

            
The call "library(tidyverse)" was missing. :)
This works for me:

ggplot(scatter_data,aes(x=x_var,y=y_var,))+
  geom_point()+
  geom_smooth(se=TRUE,fill="blue",color="black",linetype="dashed") +
  geom_ribbon(stat="smooth", aes(ymin=after_stat(ymin), ymax=after_stat(ymax)), fill=NA, color="black")+
  theme_cowplot()

Cheers,
	
	Berwin
#
+ geom_ribbon(stat = "smooth",
              se = TRUE,
              alpha = 0, # or, use fill = NA
              colour = "black",
              linetype = "dotted")

Does that work?
On Sat, 12 Aug 2023, 06:12 Rui Barradas, <ruipbarradas at sapo.pt> wrote:

            

  
  
#
Colleagues,

Your suggestions are elegant and greatly appreciated.

Thomas Subia
On Friday, August 11, 2023 at 11:08:42 PM PDT, Berwin A Turlach <berwin.turlach at gmail.com> wrote:
G'day Thomas,

On Sat, 12 Aug 2023 04:17:42 +0000 (UTC)
Thomas Subia via R-help <r-help at r-project.org> wrote:

            
The call "library(tidyverse)" was missing. :)
This works for me:

ggplot(scatter_data,aes(x=x_var,y=y_var,))+
? geom_point()+
? geom_smooth(se=TRUE,fill="blue",color="black",linetype="dashed") +
? geom_ribbon(stat="smooth", aes(ymin=after_stat(ymin), ymax=after_stat(ymax)), fill=NA, color="black")+

? theme_cowplot()


Cheers,
??? 
??? Berwin