r - 如何将 ggplot 对象存储在 R 的数据框中?

标签 r ggplot2

我有一个嵌套数据集,其中包含 4 列:图(存储 ggplot 对象)、数据(用于制作图的数据集)以及 x ('a'、'b'、'c') 和 y (' d'、'e'、'f')(图中使用的变量)。

问题是我缺少一些 y 变量,因此当我尝试使用循环将它们全部粘贴到牌组中时,我收到错误。

为了解决这个问题,我正在制作一个数据集,该数据集包含 x 和 y 的所有组合,并且有一个空图。这样,代码就会运行,如果用户不期望这样,他们可以更深入地挖掘。

问题是当我尝试将 ggplot 对象放入数据框中时,我不断收到错误:

Error in `mutate()`:
! Problem while computing `plots = empty_plots`.
✖ `plots` must be a vector, not a `gg/ggplot` object.

当我没有为嵌套数据集获取此信息时,为什么会得到此信息?如何修复此问题?

示例数据:

library(dplyr)
library(tidyr)
library(ggplot2)

#Test data with all combos of x and y
test_data <- tibble(x = c("a", "b", "c"),
                    y = c('d', "e", "f")) %>%
  expand(x, y)

#Make my empty plot

empty_plots <- ggplot() +
           theme_void() +
           geom_text(aes(0,0,label='You did not have enough data to make this plot. \n If this is unexpected, check code.')) +
           xlab(NULL)

test_data_with_plots <- test_data %>%
  mutate(plots = empty_plots)

对于最终输出,我想要一个包含 3 列的数据框——x、y 和图,其中包含空的 ggplot 对象。

谢谢!

最佳答案

它可以包装在 list 中,因为 ggplot 对象具有列表结构 - mutate 期望列的长度与原始数据列相同。如果我们仅通过 length 标准进行检查,则它与数据的行数相同

> str(empty_plots)
List of 9
 $ data       : list()
  ..- attr(*, "class")= chr "waiver"
 $ layers     :List of 1
  ..$ :Classes 'LayerInstance', 'Layer', 'ggproto', 'gg' <ggproto object: Class LayerInstance, Layer, gg>
    aes_params: list
...
> length(empty_plots)
[1] 9

但是,为了使 ggplot 正常工作,它应该是单个 block 单元,而不是拆分为多个元素。所以我们将其包装在一个列表中。

library(dplyr)
test_data_with_plots <- test_data %>%
   mutate(plots = list(empty_plots))

-输出

> test_data_with_plots
# A tibble: 9 × 3
  x     y     plots 
  <chr> <chr> <list>
1 a     d     <gg>  
2 a     e     <gg>  
3 a     f     <gg>  
4 b     d     <gg>  
5 b     e     <gg>  
6 b     f     <gg>  
7 c     d     <gg>  
8 c     e     <gg>  
9 c     f     <gg>  

可以利用list结构为每行添加每个元素

> test_data %>%
    mutate(plots = c(empty_plots))
# A tibble: 9 × 3
  x     y     plots           
  <chr> <chr> <named list>    
1 a     d     <waiver>        
2 a     e     <list [1]>      
3 a     f     <ScalsLst>      
4 b     d     <uneval>        
5 b     e     <theme>         
6 b     f     <CrdCrtsn>      
7 c     d     <FacetNll>      
8 c     e     <env>           
9 c     f     <named list [3]>

但是,以后可能无法使用

关于r - 如何将 ggplot 对象存储在 R 的数据框中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75583412/

相关文章:

r - 计算连续密度图下的面积

r - geom_smooth() : One line, 不同的颜色

arrays - 将数组转换为数据框

r - ggplot2 默认的蓝色和灰色 - 它们具体是什么 'blue' 和 'grey'

r - 扩展ggplot中定性变量的限制

r - 如何用ggplot删除空白面?

r - Boxplot,如何匹配异常值的颜色来填充美学?

r - 更新现有 Rdata 文件

r - 测试模型参数的整洁方法

mysql - 当通过批处理文件调用的脚本执行时,R 的 dbConnect 失败并显示 "DSN error"