Home > Software engineering >  R geom_smooth custom best fitted line formula
R geom_smooth custom best fitted line formula

Time:02-15

Geom_smooth formula

I am currently trying to fit a line to my data.

However, no fitted line is shown on the plot with none of the default methods of geom_smooth.

Here is the code that generated the plot:

p1 <- ggplot(data[ which(data$subject_id == "P121" & !is.na(data$col1)), ], aes(x = date, y= col1))   
  geom_point(colour= met.brewer("Isfahan1", 1))   
  geom_smooth(method = "stats::loess", se= FALSE)  
  theme(axis.title.x=element_blank(), axis.text.x=element_blank(),
                      axis.ticks.x=element_blank(), axis.title.y=element_blank(), axis.text.y=element_blank(),
                      axis.ticks.y =element_blank(), legend.title=element_blank())  
  scale_color_manual(values=met.brewer("Isfahan1", 13))

enter image description here

You can also use another method, e.g. linear

df %>%  ggplot(aes(date, col1))   
  geom_point(colour= met.brewer("Isfahan1", 1))   
  geom_smooth(formula = y~x, method = "lm", se= FALSE)   
  theme(
    axis.title.x=element_blank(), 
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(), 
    axis.title.y=element_blank(), 
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(), 
    legend.title=element_blank())  
  scale_color_manual(values=met.brewer("Isfahan1", 13))

enter image description here

However, pay attention to the data you give to the ggplot function. If your date variable is not of numeric type, however, plot will be created without smooth path.

df = tibble(
  date = 1:55 %>% as.character(),
  col1 = ifelse(date %in% i1, 200, 100)
)

df %>%  ggplot(aes(date, col1))   
  geom_point(colour= met.brewer("Isfahan1", 1))   
  geom_smooth(formula = y~x, method = "loess", se= FALSE)   
  theme(
    axis.title.x=element_blank(), 
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(), 
    axis.title.y=element_blank(), 
    axis.text.y=element_blank(),
    axis.ticks.y=element_blank(), 
    legend.title=element_blank())  
  scale_color_manual(values=met.brewer("Isfahan1", 13))

enter image description here

As you can see in this example, I changed the value of the variable date to type character (date = 1:55 %>% as.character()) which made geom_smooth to not draw anything.

CodePudding user response:

Thanks a lot for the detailed answer, everyone. The issue was about the data type I am using. It's binary (yes/no) data so it makes sense that no line will be fitted by geom_smooth. Thanks a lot again.

  • Related