HappyPy
HappyPy

Reputation: 10697

geom_smooth lm line not drawn - ggplot2

I'm trying to plot the lm line using this code

df <- data.frame(c1=factor(c(1,1,1,1,2,2,2,2,3,3,3,3)),c2=c(65,42,56,75,43,43,21,23,12,12,21,11))
p <- ggplot(aes(x=c1,y=c2),data=df)
p + geom_point() + geom_smooth(method="lm")

But the lm line is not shown. Am I missing something?

Upvotes: 2

Views: 779

Answers (1)

akrun
akrun

Reputation: 887991

The reason is that c1 is a factor. Converting it to numeric will solve the problem

library(dplyr)
library(ggplot2)
df %>%
  mutate(c1 = as.numeric(as.character(c1)) %>%
  ggplot(aes(x = c1, y = c2)) +
    geom_point() + 
    geom_smooth(method="lm")          

Upvotes: 2

Related Questions