0

假设我有以下功能:

library(ggplot2)
library(patchwork)
subplots <- function(data) {
  lst <- list()
  # Assigning first and second variable to the list
  for (i in 1:2) {
    lst[[i]] <- ggplot() +
      aes(x = 1:length(data[, i]), y = data[, i]) +
      geom_line()
  }
  # Plotting variables stored in the list 
  wrap_plots(lst)
}

此代码的主要目的是获取数据框并并排绘制第一个和第二个变量的图。但是,如果我在相同的数据上运行此代码:

sed.seed(42)
vec_1 <- rnorm(100)
vec_2 <- runif(100)
df <- data.frame(vec_1, vec_2)
subplots(df) 

我获得了第二个变量图的两倍,而不是第一个和第二个。 在此处输入图像描述

你知道如何修复吗?我是否错误地分配列表?

4

1 回答 1

1

您的列表分配很好,但您的ggplot()调用语法不正确。

尝试:

subplots <- function(data) {
  lst <- list()
  # Assigning first and second variable to the list
  for (i in 1:2) {
    lst[[i]] <- ggplot(data.frame(x = 1:length(data[, i]), y = data[, i]), aes(x = x, y = y)) +
      geom_line()
  }
  # Plotting variables stored in the list 
  wrap_plots(lst)
}
于 2021-01-21T13:01:33.863 回答