如何将 ggplot2 应用于数据框中的每一行

How to apply ggplot2 to each row in a data frame

我想将 ggplot2 可视化编码为函数,然后 apply 数据帧每一行的函数(我想使用 apply 来避免 for 循环,按照建议 .)

数据:

library(ggplot2)
point1 <- c(1,2)
point2 <- c(2,2)

points <-as.data.frame(rbind(point1,point2))

我将 points 保存为数据框,它在 ggplot2 中运行良好:


ggplot(data = points) +
    geom_point(aes(x = points[, 1], y = points[, 2])) +
    xlim(-3, 3) +
    ylim(-3, 3) +
    theme_bw()

虽然那不是我真正想要的情节:我想要 两个情节,每个情节有一点。

现在我构建一个循环遍历数据框行的函数:


plot_data <- function(data) {
  ggplot(data) +
    geom_point(aes(x = data[, 1], y = data[, 2])) +
    xlim(-3, 3) +
    ylim(-3, 3) +
    theme_bw()
}

我创建了一个列表来存储绘图:

myplots <- list()

这是对 apply 的调用,紧随 this suggestion:

myplots <- apply(points, 1, plot_data)

但我收到以下错误:

#> Error: `data` must be a data frame, or other object coercible by `fortify()`, 
not a numeric vector

但是我的数据一个数据框。

这是因为:“apply() 将尝试将 data.frame 转换为矩阵(请参阅帮助文档)。如果由于混合数据类型而无法正常转换,我不太确定会产生什么结果”,正如我提到的 the answer 的评论中所述?

不过,如果我在调用申请后检查数据 class,数据仍然是一个数据帧:

class(points)
#> [1] "data.frame"

reprex package (v0.3.0)

于 2021-04-09 创建

正如评论中 Gregor Thomas 所建议的那样:

library(ggplot2)
point1 <- c(1, 2)
point2 <- c(2, 2)

points <- as.data.frame(rbind(point1, point2))

plot_data <- function(data) {
  ggplot(data) +
    geom_point(aes(x = data[, 1], y = data[, 2])) +
    xlim(-3, 3) +
    ylim(-3, 3) +
    theme_bw()
}
myplots <- list()
myplots <- lapply(1:nrow(points), function(i) plot_data(points[i, ]))
myplots
#> [[1]]

#> 
#> [[2]]

reprex package (v0.3.0)

于 2021-04-09 创建