首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从嵌套列表中提取每个ggplot2图

如何从嵌套列表中提取每个ggplot2图
EN

Stack Overflow用户
提问于 2019-04-17 16:06:45
回答 1查看 1.1K关注 0票数 7

创建大型嵌套列表以跟踪用ggplot2创建的地块通常很方便。

例如,下面是我如何将少数几个情节存储在一个大的情节列表中,其中包括主题和子主题的子列表。

summary_plots

  1. $Demographics
    • Demographics$Socioeconomic$Household_Income_Plot
    • Demographics$Socioeconomic$Education_Plot
    • Demographics$Age_Plot

  1. $Product_Usage
    • Purchase_Frequency_Plot
    • ……

如何从整个列表中提取所有ggplot2绘图对象?我想要能够创建一个“单位”,一级列表,包含所有的情节,包含在原来的列表。

下面是一个简单的示例列表:

代码语言:javascript
复制
generic_plot <- ggplot(mtcars) + geom_point(aes(x = wt, y = mpg)) 

summary_plots <- list() 
summary_plots$Demographics$Socioeconomic$Income <- generic_plot 
summary_plots$Demographics$Socioeconomic$Education <- generic_plot 
summary_plots$Demographics$Age <- generic_plot 
summary_plots$Product_Usage$Purchase_Frequency <- generic_plot

所需的结果相当于创建如下列表:

代码语言:javascript
复制
list('Demographics.Socioeconomic.Income' = generic_plot,
     'Demographics.Socioeconomic.Education' = generic_plot,
     ...)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-04-17 17:23:07

The code written in this answer by @Michael将完成这一任务,只需稍作修改。

如果我们将morelists <- ...行中的morelists <- ...检查更改为仅在类包含'list'而非是否包含类'gg'的情况下扁平化,那么它将不会平铺这些情节,并将返回一个平面列表。

代码语言:javascript
复制
flattenlist <- function(x){  
    morelists <- sapply(x, function(xprime) {
        'list' %in% class(xprime) & !('gg' %in% class(xprime))
    })
    out <- c(x[!morelists], unlist(x[morelists], recursive=FALSE))
    if(sum(morelists)){ 
        Recall(out)
    }else{
        return(out)
    }
}


plts <- flattenlist(summary_plots)

names(plts)

[1] "Demographics.Age"                    
[2] "Product_Usage.Purchase_Frequency"    
[3] "Demographics.Socioeconomic.Income"   
[4] "Demographics.Socioeconomic.Education"


lapply(plts, class)

$Demographics.Age
[1] "gg"     "ggplot"

$Product_Usage.Purchase_Frequency
[1] "gg"     "ggplot"

$Demographics.Socioeconomic.Income
[1] "gg"     "ggplot"

$Demographics.Socioeconomic.Education
[1] "gg"     "ggplot"
票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55731855

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档