【问题标题】:printing ggplot with purrr map使用 purrr 地图打印 ggplot
【发布时间】:2019-10-02 15:15:57
【问题描述】:

我想针对我的response variablenumeric cols 创建ggplots

这是可重现的代码:

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)`? 

得到错误:

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

怎么了?

【问题讨论】:

  • 你有data=.xaes(y=.x)。其中一个.x 需要是data.frame/tibble,另一个需要是列名。你到底想画什么?
  • 试图将cyl 与所有其他numeric cols 进行对比
  • 澄清一下,您不希望按组绘制任何图,而是寻找针对其他变量绘制的cyl

标签: r ggplot2 purrr


【解决方案1】:

当我们想要遍历一堆变量并将它们中的每一个与另一个变量进行对比时,一个选择是遍历变量名。

我会先在y 上提取我想要的变量名。我在管道的末尾使用set_names() 以自身命名向量,因为有时我需要稍后进行组织。

vars = mpg %>%
     select_if(is.numeric) %>%
     select(-cyl, - year) %>%
     names() %>%
     set_names()

结果是一个字符串向量。

vars
# displ     cty     hwy 
# "displ"   "cty"   "hwy" 

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

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

如果您有兴趣了解更多解释,我将演示以上in a blog post I wrote last year 的方法。

如果您不想像这样循环遍历字符串,另一种选择是将数据集重塑为长格式,然后使用嵌套方法。这个想法是制作一个长数据集,将所需的变量放在 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)))

【讨论】:

  • 这是什么魔法 :D 厉害了我的朋友 :)
猜你喜欢
  • 2015-12-22
  • 1970-01-01
  • 2021-04-18
  • 1970-01-01
  • 2015-10-05
  • 2015-03-10
  • 2021-12-30
  • 1970-01-01
  • 2019-01-18
相关资源
最近更新 更多