用 purrr 地图打印 ggplot

She*_*ery 4 r ggplot2 purrr

我想创建ggplotsnumeric cols反对我response variable

这是可重现的代码:

test = mpg %>% select_if(is.numeric) %>% 
dplyr::select(-year) %>% nest(-cyl) %>% 
mutate(ggplots = map(data,~ggplot(data = .x) + geom_point(aes(x = cyl, y = .x))))

test
# A tibble: 4 x 3
    cyl           data ggplots
  <int> <list<df[,3]>> <list> 
1     4       [81 x 3] <gg>   
2     6       [79 x 3] <gg>   
3     8       [70 x 3] <gg>   
4     5        [4 x 3] <gg>   
Warning message:
All elements of `...` must be named.
Did you want `data = c(displ, cty, hwy)`? 
Run Code Online (Sandbox Code Playgroud)

得到错误:

test$ggplots[[1]]
Don't know how to automatically pick scale for object of type tbl_df/tbl/data.frame. Defaulting to continuous.
Error: Aesthetics must be either length 1 or the same as the data (81): x, y
Run Code Online (Sandbox Code Playgroud)

怎么了?

aos*_*ith 9

当我们想要遍历一堆变量并将它们中的每一个与另一个变量作图时,一个选择是遍历变量名称。

我会首先在y. 我set_names()在管道的末尾使用它自己命名向量,因为有时我需要稍后进行组织。

vars = mpg %>%
     select_if(is.numeric) %>%
     select(-cyl, - year) %>%
     names() %>%
     set_names()
Run Code Online (Sandbox Code Playgroud)

结果是一个字符串向量。

vars
# displ     cty     hwy 
# "displ"   "cty"   "hwy" 
Run Code Online (Sandbox Code Playgroud)

现在我可以遍历这些变量名称并针对固定x变量绘制一个图cyl。我将purrr::map()为此使用一个循环。由于我正在处理字符串,因此我需要在 中使用 tidy 评估ggplot(),并使用.data代词完成(我相信这仅适用于rlang的最新 0.4.0 版本)。我用变量 in 标记 y 轴labs(),否则它.data在轴标签中有代词。

plots = map(vars, ~ggplot(data = mpg) +
                 geom_point(aes(x = cyl, y = .data[[.x]]) ) +
                 labs(y = .x)
)
Run Code Online (Sandbox Code Playgroud)

如果您对更多解释感兴趣,我在去年写的一篇博客文章中演示了上述方法。

如果您不想像这样循环遍历字符串,另一种选择是将数据集重塑为长格式,然后使用嵌套方法。这个想法是制作一个长数据集,在 y 轴上获取您想要的变量并将它们的值放在一起在一列中。我用tidyr::pivot_longer(). y变量的数值现在位于一个名为 的列中value

然后为每个变量名称嵌套cylvalue列。完成后,您将拥有一个三行数据集,每个y变量一行,您可以mutate()像原始尝试一样遍历数据集以创建绘图列。

plots2 = mpg %>%
     select_if(is.numeric) %>% 
     dplyr::select(-year) %>% 
     pivot_longer(cols = -cyl) %>% 
     nest(data = -name) %>%
     mutate(ggplots = map(data, 
                          ~ggplot(data = .x) + geom_point(aes(x = cyl, y = value)))
Run Code Online (Sandbox Code Playgroud)