user4339431
user4339431

Reputation:

Why will geom_smooth() not render a regression line?

library(readr)
library(ggplot2)
MERGED2014_15_PP <- read_csv("~/Desktop/R/Database Camp - Day 1/CollegeScorecard_Raw_Data/MERGED2014_15_PP.csv")
a1 = subset(MERGED2014_15_PP, STABBR == "AL")
a3 = geom_point(aes(color=factor(CITY)))
a8 = subset(a1, !(SATMTMID=="NULL"), !(SATVRMID=="NULL"))
a9 = ggplot(a8, aes(y = as.numeric(SATVRMID), x = as.numeric(SATMTMID), text = INSTNM, text2 = CITY))
a11 = geom_smooth(method = lm)
a12 = geom_text(aes(label=""))
a9 + a3 + a12 + a11

In the above code, when I attempt to run it no regression line appears. However, I also receive no errors. The data I am using is from the US Department of Education College Scorecard. What could be causing my error and how could I fix it? This code generated the below: Example of R output After cleaning up a8 to only include SATMTMID and SATVRMID, dput() returns the below:

structure(list(SATMTMID = c("420", "565", "590", "430", "565", 
"509", "588", "560", "400", "490", "485", "558", "465", "528", 
"484", "450", "558", "518", "538", "424", "465"), SATVRMID = c("424", 
"570", "595", "425", "555", "486", "575", "560", "420", "510", 
"495", "550", "470", "548", "506", "476", "565", "510", "535", 
"448", "455")), .Names = c("SATMTMID", "SATVRMID"), row.names = c(NA, 
-21L), class = c("tbl_df", "tbl", "data.frame"))

Upvotes: 0

Views: 1439

Answers (1)

Ben Bolker
Ben Bolker

Reputation: 226427

tl;dr I'm not quite sure why, but I think your addition of the text and text2 mappings is messing things up. I'm not sure what these are supposed to do in your real use case ... I think it's probably having the effect of putting every institution in its own, unique group; you could also try adding aes(group=1) to the geom_smooth() specification.

I went and got the data myself. I slightly modified your cleaning pipeline (but this doesn't really do anything different from what you do above ...)

## https://collegescorecard.ed.gov/data/
library(readr)
library(ggplot2)
library(dplyr)
dd <- read_csv("MERGED2014_15_PP.csv")
dd2 <- dd %>%
    filter(STABBR=="AL") %>%
    select(SATMTMID,SATVRMID,INSTNM,CITY) %>%
    mutate(SATMTMID=as.numeric(SATMTMID),
           SATVRMID=as.numeric(SATVRMID),
           CITY=factor(CITY)) %>%
    na.omit %>%
    droplevels %>%
    mutate(CITY=reorder(CITY,SATMTMID))

Now make the plot:

library(ggrepel)
theme_set(theme_bw())  ## my preference
ggplot(dd2,aes(y = SATVRMID, x = SATMTMID))+
    geom_point(aes(color=CITY))+
    geom_smooth(method=lm)+
    geom_text_repel(aes(label=INSTNM,color=CITY))+
    labs(x="median math SAT",y="median verbal SAT")

enter image description here

Upvotes: 2

Related Questions