ggplot geom_smooth() 用于线性回归虚拟变量 - 无回归线

问题描述 投票:0回答:1

对于我在这个平台上提出的第一个问题,我提前表示歉意。我浏览了很多线程,但我发现的大多数内容都不涉及任何虚拟变量。 然而,经过大约 4 个小时的调查后,我似乎无法找出问题所在。

出于教学和演示的目的,我目前正在尝试使用众所周知的 iris 数据集设置一个虚拟变量线性模型的小图。

但是,无论我尝试什么,我都无法让它同时绘制多条回归线,而我期待两条:一条从 versicolor 到 setosa,一条从 virginica 到 setosa,其中 setosa 是第一组因素。

这是我的代码以及我到目前为止所尝试过的。

#加载 tidyverse。

library(tidyverse)

#加载鸢尾花数据集并将其保存为对象。

dataset <- as_tibble(iris)

#作为背景:我想可视化以下线性回归。

ols_lm_iris_all <- lm(Petal.Length ~ Species,
                      data = dataset)

summary(ols_lm_iris_all)

#这会产生以下 lm 模型,该模型给出了两两比较:versicolor 与 setosa 以及 virginica 与 setosa。到目前为止一切顺利。

#我可视化数据的代码如下。

iris_lm_plot_all <- ggplot(dataset, aes(x = Species, y = Petal.Length, colour = Species)) +
                    geom_smooth(method = lm, aes(group = Species)) +
                    geom_jitter(width = 0.2) +
                    labs(title = "Linear OLS regression with two regression lines for three types of Iris.")

iris_lm_plot_all

#然而,我最终得到的是一个带有抖动的散点图,但根本没有任何回归线。

#这是我也尝试过的,部分成功。如果我们指定“aes(group = 1)”而不是 group = Species,我们会得到从最后一个因子 virginica 到 setosa 的一条 lm 线。这是工作的一半,但现在我们还没有把杂色变成山毛榉。

iris_lm_plot_all <- ggplot(dataset, aes(x = Species, y = Petal.Length, colour = Species)) +
                    geom_smooth(method = lm, aes(group = 1)) +
                    geom_jitter(width = 0.2) +
                    labs(title = "Linear OLS regression mit with two regression line for three types of Iris.")

我还想到:难道geom_smooth没有正确处理物种的虚拟化?

你有什么想法吗?

非常感谢!

r ggplot2 linear-regression dummy-variable
1个回答
0
投票

最终的情节并没有达到你所希望的那样。物种被转换为数字,然后 lm 适合所有三个因子。在这个例子中,它很好地遍历了第一个和最后一个簇,但如果对因子重新排序,则不会发生这种情况。

您可以手动编辑两个比较/三个因素的数据,但这并不容易概括:

dataset <- as.tibble(iris)

dataset <- rbind(
  cbind(subset(dataset, as.numeric(Species) %in% c(1,2)),comparison="A"),
  cbind(subset(dataset, as.numeric(Species) %in% c(1,3)),comparison="B")
)

ggplot(dataset, aes(x = Species, y = Petal.Length, colour = Species)) +
    geom_smooth(method = lm, aes(group=comparison)) +
  geom_jitter(width = 0.2, ) +
  labs(title = "Linear OLS regression mit with two regression line for three types of Iris.")

这个问题还有其他绘制成对比较的方法。

© www.soinside.com 2019 - 2024. All rights reserved.