继续我的工作与功能和ggplot:
我整理了一些基本的方法,说明如何使用lapply和ggplot循环通过一个y_columns列表来生成一些单独的情节:
require(ggplot2)
# using lapply with ggplot
df <- data.frame(x=c("a", "b", "c"), col1=c(1, 2, 3), col2=c(3, 2, 1), col3=c(4, 2, 3))
cols <- colnames(df[2:4])
myplots <- vector('list', 3)
plot_function <- function(y_column, data) {
ggplot(data, aes_string(x="x", y=y_column, fill = "x")) +
geom_col() +
labs(title=paste("lapply:", y_column))
}
myplots <- lapply(cols, plot_function, df)
myplots[[3]])

我知道如何引入第二个变量,我将使用它来选择行。在我的最小示例中,我跳过了选择,只是重复使用与前面相同的绘图和dfs,我只添加了3次迭代。因此,我想生成与上面相同的三幅图,但现在标记为迭代A、B和C。
我花了一段时间来整理语法,但现在我得到mapply需要相同长度的向量,这些向量以匹配对的形式传递给函数。因此,我使用expand.grid生成变量1和变量2的所有对来创建数据,然后通过mapply传递第一和第二列。要解决的下一个问题是,我需要将数据作为列表MoreArgs =传递。所以看起来一切都应该是好的。对于aes_string(),我使用的语法与lapply示例中的语法相同。
但是,由于某些原因,它现在没有正确地评估y_column,而是简单地将其作为一个绘图的值,而不是作为标记df$col1中包含的值的指标。
帮助!
require(ggplot2)
# using mapply with ggplot
df <- data.frame(x=c("a", "b", "c"), col1=c(1, 2, 3), col2=c(3, 2, 1), col3=c(4, 2, 3))
cols <- colnames(df[2:4])
iteration <- c("Iteration A", "Iteration B", "Iteration C")
multi_plot_function <- function(y_column, iteration, data) {
plot <- ggplot(data, aes_string(x="x", y=y_column, fill = "x")) +
geom_col() +
labs(title=paste("mapply:", y_column, "___", iteration))
}
# mapply call
combo <- expand.grid(cols=cols, iteration=iteration)
myplots <- mapply(multi_plot_function, combo[[1]], combo[[2]], MoreArgs = list(df), SIMPLIFY = F)
myplots[[3]]

发布于 2020-12-13 18:32:43
我们可能需要在这里使用行
out <- lapply(asplit(combo, 1), function(x)
multi_plot_function(x[1], x[2], df))在OP的代码中,唯一的问题是列是“组合体”的factor,因此没有正确地解析它。如果我们将它更改为character,它就能工作
out2 <- mapply(multi_plot_function, as.character(combo[[1]]),
as.character(combo[[2]]), MoreArgs = list(df), SIMPLIFY = FALSE) -testing
out2[[1]]

https://stackoverflow.com/questions/65279156
复制相似问题