2

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?

HappyPy
  • 9,839
  • 13
  • 46
  • 68
  • Possible duplicate of https://stackoverflow.com/questions/15633714/adding-a-regression-line-on-a-ggplot – akrun May 05 '18 at 14:56
  • 1
    Why is 'c1' a `factor`? Change it to `numeric` and you should be able to get the line – akrun May 05 '18 at 15:02
  • 2
    If you do happen to require a `factor`, set `aes(group = 1)`. – Axeman May 05 '18 at 15:03
  • 1
    @Axeman: Thanks, that was it! Could you turn your comment into an answer so that I can accept it? – HappyPy May 05 '18 at 15:06
  • [Possible duplicate](https://stackoverflow.com/questions/34608767/add-geom-smooth-to-boxplot/34609280#34609280). – Axeman May 05 '18 at 15:08

1 Answers1

2

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")          
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
akrun
  • 874,273
  • 37
  • 540
  • 662