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

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

我有一个示例将数据嵌入到列表中,为列表中的每个tibble添加线性模型,将回归系数添加到列表中的每个记录,并将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的任何建议都会非常适合。

r ggplot2 nested tidyverse purrr
1个回答
2
投票

您用于mapplot 2函数仅映射data,对于截距和斜率,它看到3个元素的向量。这就是你在每个情节中看到3行的原因。

你必须使用pmapmap你需要为每个情节使用的所有信息/列。

试试这个:

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')
  )
  ) 
© www.soinside.com 2019 - 2024. All rights reserved.