【问题标题】:Plotting categorical variables OLS in R在 R 中绘制分类变量 OLS
【发布时间】:2019-04-14 14:45:17
【问题描述】:

我正在尝试使用来自lm() 函数。

goutdata <- read.table("gout.txt", header = TRUE)
goutdata$sex <- factor(goutdata$sex,levels = c("M",  "F"))
goutdata$race <- as.factor(goutdata$race)

fm <- lm(su~sex+race+age, data = goutdata)
summary(fm)
ggplot(fm, aes(x= age, y = su))+xlim(30, 70) + geom_jitter(aes(age,su, colour=age)) + facet_grid(sex~race)

我尝试使用带有 ggplot 的 facet_wrap() 函数来处理分类变量,但我只想创建一个图。我正在尝试 geom_jitter 和 geom_smooth 的组合,但我不确定如何将 geom_smooth() 与分类变量一起使用。任何帮助,将不胜感激。

数据:https://github.com/gdlc/STT465/blob/master/gout.txt

【问题讨论】:

  • 您需要根据年龄设置颜色吗?因为最直接的方法可能是创建线/点/任何东西,并根据性别和种族设置它们的颜色/线型/形状
  • 我不需要,不。

标签: r ggplot2 lm


【解决方案1】:

我们可以使用interaction() 即时创建分组并直接在geom_smooth() 内执行OLS。在这里,它们被分组在一个地块上:

ggplot(goutdata, aes(age, su, color = interaction(sex, race))) +
  geom_smooth(formula = y~x, method="lm") +
  geom_point() +
  hrbrthemes::theme_ipsum_rc(grid="XY")

并且,展开成多个方面:

ggplot(goutdata, aes(age, su, color = interaction(sex, race))) +
  geom_smooth(formula = y~x, method="lm") +
  geom_point() +
  facet_wrap(sex~race) +
  hrbrthemes::theme_ipsum_rc(grid="XY")

您现在已经得到了https://github.com/gdlc/STT465/blob/master/HW_4_OLS.md 中#1 的部分答案:-)

【讨论】:

    【解决方案2】:

    您或许可以使用geom_smooth() 来显示回归线?

    dat <- read.table("https://raw.githubusercontent.com/gdlc/STT465/master/gout.txt", 
                       header = T, stringsAsFactors = F)
    
    library(tidyverse) 
    
    dat %>%
      dplyr::mutate(sex = ifelse(sex == "M", "Male", "Female"),
                    race = ifelse(race == "W", "Caucasian", "African-American"),
                    group = paste(race, sex, sep = ", ")
                    ) %>%
      ggplot(aes(x = age, y = su, colour = group)) +
      geom_smooth(method = "lm", se = F, show.legend = F) +
      geom_point(show.legend = F, position = "jitter", alpha = .5, pch = 16) +
      facet_wrap(~group) +
      ggthemes::theme_few() +
      labs(x = "Age", y = "Expected serum urate level")
    

    【讨论】:

      猜你喜欢
      • 2019-09-08
      • 1970-01-01
      • 1970-01-01
      • 2015-10-16
      • 2020-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-15
      相关资源
      最近更新 更多