将 ggplot 存储到按顺序命名的对象中

问题描述 投票:0回答:1

我试图循环遍历一系列列(每个数据集中的列数可变),为每个列生成一个时间序列,然后将此图存储为 ggplot 对象,然后我可以将其排列到网格中。到目前为止我的代码:

for (i in 2:ncol(df)){

×<- df[,1] y[,i] <- df[,i]

分配(粘贴(“曲线”,i,sep =“”),ggplot(数据= y,aes(x = x,y = y [,i]))+ geom_point() + geom_smooth(方法 = 'lm', 公式 = y~poly(x,3))

}

这样,我明确地为每个 ggplot 命名一个不同的名称,我应该能够将其排列到网格中。问题是只存储了最新的 ggplot,并且我的所有对象都返回完全相同的图,尽管它们是从不同的数据生成的。

我之前尝试过一种将 ggplots 存储到列表中的解决方案,结果相同。

示例数据框:

x a b c d 1 2 3 8 10 2 4 6 7 14 3 6 8 6 24 4 8 3 5 34 5 10 3 4 43 6 12 1 4 32 7 14 5 3 43 8 16 7 1 64 9 18 8 3 75 10 20 3 2 23

提前致谢!

ggplot2 grid assign
1个回答
0
投票

只需使用列名称作为键将各个图存储在列表中。我不完全确定您尝试过的

assign
paste
方法,在下面我尝试在稍微清理代码并依次执行操作后重新创建您的输出。

library(ggplot2)

# sample dataframe
df <- data.frame(
  x = 1:10,
  a = c(2, 4, 6, 8, 10, 12, 14, 16, 18, 20),
  b = c(3, 6, 8, 3, 3, 1, 5, 7, 8, 3),
  c = c(8, 7, 6, 5, 4, 4, 3, 1, 3, 2),
  d = c(10, 14, 24, 34, 43, 32, 43, 64, 75, 23)
)

# initialize an empty list to store ggplot objects
plot_list <- list()

# loop through columns and create ggplot objects
for (i in 2:ncol(df)) {
  col_name <- colnames(df)[i]
  x <- df$x
  y <- df[, i]
  
  p <- ggplot(data = data.frame(x = x, y = y), aes(x = x, y = y)) +
    geom_point() +
    geom_smooth(method = 'lm', formula = y ~ poly(x, 3)) +
    labs(title = paste("curve", col_name))
    
  plot_list[[col_name]] <- p
}

# print the plots from the list
print(plot_list)

© www.soinside.com 2019 - 2024. All rights reserved.