【问题标题】:A function to create multiple plots by subsets of data frame通过数据框的子集创建多个图的函数
【发布时间】:2015-07-31 16:34:04
【问题描述】:

我有一个 27,538 x 29 的数据框 (NBA_Data)。其中一列称为“月”,有八个月(十月:六月)。我想编写一个函数,按月自动对该数据帧进行子集化,然后在 ggplot2 中创建 8 个绘图对象。我在这里超出了我的深度,但我想这些将存储在一个列表中(“我的情节”)。

我计划对每个绘图对象使用 geom_plot 来绘制 Points 和 Minutes.Played。我不熟悉 grid.arrange,但我猜一旦我有了“我的地块”,我就可以(以某种形式)将它用作 grid.arrange 的参数。

我试过了:

empty_list <- list()
    for (cat in unique(NBA_Data$month)){
      d <- subset(NBA_Data, month == cat)
    empty_list <- c(empty_list, d) 
    }

这给出了一个完整的列表,每个月重复所有 29 列,长度为 261。不理想,但可能可行。然后我尝试使用 lapply 来拆分列表,但我搞砸了。

lapply(empty_list, split(empty_list, empty_list$month))

Error in match.fun(FUN) : 
'split(x = empty_list, f = empty_list$month)' is not a function, character or symbol
In addition: Warning message:
In split.default(x = empty_list, f = empty_list$month) :
data length is not a multiple of split variable

有什么建议吗? 谢谢。

【问题讨论】:

    标签: r


    【解决方案1】:

    您已经可以使用 split 将数据集分块为列表:

    list <- split(data, data$month)
    

    如果您正在使用 ggplot,您还可以使用 facet_wrap 在同一页上使用相同的数据制作多个绘图。

    library(ggplot2)
    ggplot(data, aes(x = PlayerName, y = PPG)) + geom_point() + facet_wrap(~month)
    

    【讨论】:

    • facet_wrap !漂亮!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-18
    • 2021-06-16
    • 2018-11-21
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    相关资源
    最近更新 更多