为什么geom_smooth()不会渲染回归线?

时间:2017-08-01 17:59:16

标签: r

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

在上面的代码中,当我尝试运行它时,不会出现回归线。但是,我也没有收到任何错误。我使用的数据来自美国教育部学院记分卡。什么可能导致我的错误,我该如何解决?此代码生成如下: Example of R output 清理a8后只包含SATMTMID和SATVRMID,dput()返回以下内容:

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"))

1 个答案:

答案 0 :(得分:1)

tl; dr 我不太确定原因,但我认为您添加texttext2映射会让事情变得混乱。我不确定这些在你的真实用例中应该做些什么...我认为它可能具有将每个机构都放在它自己独特的群体中的效果;您也可以尝试将aes(group=1)添加到geom_smooth()规范。

我自己去了解数据。我略微修改了你的清洁管道(但是这并没有做到与你上面所做的不同......)

## 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))

现在制作情节:

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