Search code examples
rggplot2smoothing

Why is geom_smooth not appearing on a grouped data frame?


My data frame looks like this, and, to my mind, plotting a line through the points should be uncontroversial and easy, but it's not appearing. I am getting a new message saying that it is using formula y~x; that did not appear when I used to use code like this. any tips are welcome. Using ggplot2 3.3.1.

#My data
library(ggplot2)
dat<-structure(list(election = c("1965", "1968", "1972", "1974", "1979", 
"1980", "1984", "1988", "1993", "1997", "2000", "2004", "2006", 
"2008", "2011", "2015", "2019"), degree = c(1, 1, 1, 1, 1, 1, 
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1), vote = c(3, 3, 3, 3, 3, 3, 
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3), n = c(21L, 10L, 18L, 29L, 70L, 
55L, 73L, 70L, 43L, 95L, 63L, 70L, 105L, 122L, 246L, 239L, 225L
), pct = c(0.144827586206897, 0.072463768115942, 0.114649681528662, 
0.0900621118012422, 0.148619957537155, 0.155807365439093, 0.17016317016317, 
0.126811594202899, 0.0622286541244573, 0.116136919315403, 0.0813953488372093, 
0.159453302961276, 0.202702702702703, 0.148599269183922, 0.219642857142857, 
0.156005221932115, 0.130057803468208)), class = c("grouped_df", 
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -17L), groups = structure(list(
    election = c("1965", "1968", "1972", "1974", "1979", "1980", 
    "1984", "1988", "1993", "1997", "2000", "2004", "2006", "2008", 
    "2011", "2015", "2019"), degree = c(1, 1, 1, 1, 1, 1, 1, 
    1, 1, 1, 1, 1, 1, 1, 1, 1, 1), .rows = list(1L, 2L, 3L, 4L, 
        5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 
        17L)), row.names = c(NA, -17L), class = c("tbl_df", "tbl", 
"data.frame")))
# Do a check
head(dat)
#PLot Smooth does not show up
dat %>% 
  ggplot(., aes(x=election, y=pct))+geom_point()+geom_smooth()

Solution

  • The problem is that the election variable is a character. Convert it to numeric before passing the argument to ggplot or change it in the aes.

    # Do a check
    head(dat)
    dat %>% 
        ggplot(.,aes(x=as.numeric(election), y=pct))+geom_point()+geom_smooth()
    

    enter image description here