在 R 中,为什么我的绘图是通过嵌套和映射生成的,我的数据显示为列表而不是 ggplot 对象?

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

我通过嵌套我的数据集并在其上映射来绘制许多图。最终,我想使用 officer 将这些图放入 PowerPoint 幻灯片中。我可以绘制图,但出于某种原因,当我嵌套并在其上映射时,R 将每个图分类为 list 而不是图。它会很好地打印它们(所以我的问题不同于 here),但是为了与 officer 集成,我需要对象是一个 ggplot(除非有人知道一种方法来覆盖 ph_with 的值参数的这个要求.. .).

当我尝试

as_ggplot(my_plot)
时,我得到

Error in gList(...) : only 'grobs' allowed in "gList"

我也按照here的建议尝试了ggplotGrob(my_plot),但这也没有用,产生

Error in UseMethod("ggplot_build") :  no applicable method for 'ggplot_build' applied to an object of class "list"
.

下面是一个可重现的示例,比较了通过 nest/map 与传统方法创建绘图:

library(purrr)
library(dplyr)
library(ggplot2)
library(tidyr)
#Nest my data by cyl
mt_nest <- mtcars %>%
  nest(data = !(cyl))

#Make all plots separated by cyl (generates 3 plots--one for each cyl)
mt_plots <- mt_nest %>%
  mutate(plots = map(
    .x = data, 
    ~ggplot(.x, aes(x = gear, y = mpg)) +
      geom_col()))

#Pulls out just one of the plots
one_plot_from_nest <- mt_plots$plots[mt_plots$cyl == 6]

#Plot prints correctly
one_plot_from_nest

#Class is showing list though
class(one_plot_from_nest)

#Why can't I force the plot to be a ggplot object?
as_ggplot(one_plot_from_nest)

#Make the same plot as above
one_plot <- mtcars %>%
  filter(cyl == 6) %>%
  ggplot(aes(x = gear, y = mpg)) +
  geom_col()

#Also prints correctly
one_plot

#This is a ggplot object
class(one_plot)
r ggplot2 tidyr purrr officer
1个回答
0
投票

我们需要提取

list
元素——因为它是一个长度为1
list

length(one_plot_from_nest)
[1] 1

class(one_plot_from_nest[[1]])
[1] "gg"     "ggplot"

原因是,在子集化时我们使用

[
作为
list
列,即绘图和
[
仍然返回列表,而如果我们使用
[[
它将提取列表元素

mt_plots$plots[mt_plots$cyl == 6]
© www.soinside.com 2019 - 2024. All rights reserved.