gpt4 book ai didi

r - 为嵌套列表中的每条记录绘制回归线

转载 作者:行者123 更新时间:2023-12-02 00:54:25 25 4
gpt4 key购买 nike

我有一个将数据嵌套到列表中的示例,向列表中的每个小标题添加一个线性模型,向列表中的每个记录添加回归系数,并向列表中的每个记录添加 2 个不同的 ggplot 对象。我想为每条记录在单独的图形上绘制回归线。我可以让 geom_smooth 完全按照我的要求去做,但是 geom_abline 似乎为列表中的每条记录添加了一个回归(我的示例有三个记录,因此每个图上有三行而不是每个图所需的单行记录。

library(tidyverse)
library(purrr)
library(broom)
library(ggplot2)

iris_species <- iris %>%
group_by(Species) %>%
nest()

# build model functions
model <- function(iris) {
lm(Sepal.Length ~ Sepal.Width, data = iris)
}

# map models to the tibble
iris_species <- iris_species %>%
mutate(model = map(data, model))

iris_species # look at the structure

# add glance and tidy results to list
iris_species <- iris_species %>%
mutate(t = map(model, tidy)
)

# unnest tidy list
iris_species_g <- iris_species %>%
unnest(t) %>%
select(Species, term, estimate) %>%
spread(key = term, value = estimate) %>%
select(Species, `(Intercept)`, Sepal.Width)

# pain down a list for species and data
iris_species_list <- iris_species %>%
select(Species, data, model)

# join
iris_species_coeffs <- left_join(iris_species_list, iris_species_g, by = 'Species')

# add figures to list
iris_species_figs <- iris_species_coeffs %>%
mutate(plot1 = map(data, ~ ggplot(., aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point() +
geom_smooth(se = TRUE, size = 1, color = 'grey')
)
)

iris_species_figs <- iris_species_figs %>%
mutate(plot2 = map(data, ~ ggplot(., aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point() +
geom_abline(intercept = `(Intercept)`, slope = Sepal.Width, color = 'blue')
)
)

iris_species_figs

# make figures
iris_species_figs$plot1 # works as expected

iris_species_figs$plot2 # does not

这是上述代码的最终产品:

# A tibble: 3 x 7
Species data model `(Intercept)` Sepal.Width plot1 plot2
<fct> <list> <list> <dbl> <dbl> <list> <list>
1 setosa <tibble [50 × 4]> <S3: lm> 2.64 0.690 <S3: gg> <S3: gg>
2 versicolor <tibble [50 × 4]> <S3: lm> 3.54 0.865 <S3: gg> <S3: gg>
3 virginica <tibble [50 × 4]> <S3: lm> 3.91 0.902 <S3: gg> <S3: gg>

运行最后两行显示问题。 plot1 中的 geom_smooth 代码使用每条记录的数据为每条记录创建 1 个图形,并将平滑线应用于每个图形。然而,plot2 中的 goem_abline 却没有。它似乎在三个数字中的每一个上绘制了所有 3 条线(每条记录一条)。任何关于如何让 goem_abline 表现得像 geom_smooth 的建议都会非常受欢迎。

最佳答案

您用于 plot 2map 函数仅映射 data 并且对于截距和斜率,它看到一个向量 3元素。这就是为什么您会在每个图中看到 3 条线。

您必须使用 pmap 才能映射每个绘图需要使用的所有信息/列。

试试这个:

iris_species_figs <- iris_species_figs %>% 
mutate(plot2 = pmap(list(data,`(Intercept)`,Sepal.Width),
function(a,b,c) ggplot(a, aes(x = Sepal.Width, y = Sepal.Length)) +
geom_point() +
geom_abline(intercept = b, slope = c, color = 'blue')
)
)

关于r - 为嵌套列表中的每条记录绘制回归线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55527777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com