首页 > 解决方案 > 为数据框的每一列创建一个图并创建一个图列表

问题描述

我想为数据框中的每一列创建一个 QQplot,然后作为绘图列表返回

我的 df 的一小部分

structure(list(LAB.ID = c(4L, 3L, 8L, 7L, 4L, 5L, 2L, 2L, 3L, 
10L, 5L, 12L, 7L, 12L, 7L, 10L, 2L, 8L, 5L, 12L, 4L, 8L, 10L, 
3L, 4L, 5L, 10L, 3L, 7L, 5L, 8L, 3L, 12L, 4L, 2L, 2L, 10L, 3L, 
4L, 8L, 2L, 5L, 10L, 12L, 7L, 7L, 8L, 12L), Fe = c(56.39, 56.83, 
56.382, 56.48, 56.43, 56.32, 55.94, 55.7, 56.54, 56.3, 56.29, 
56.11, 56.4, 56.46, 56.54, 56.5, 56.59, 56.258, 56.31, 56.1, 
56.53, 56.442, 56.2, 56.18, 56.31, 56.32, 56.5, 56.5, 56.43, 
56.39, 56.258, 56.51, 56.35, 56.47, 56.5, 55.98, 56.7, 56.34, 
56.35, 56.532, 55.93, 56.32, 56.5, 56.36, 56.73, 56.62, 56.264, 
56.37), SiO2 = c(7.67, 7.84, 7.936, 7.77, 7.74, 7.91, 7.63, 7.65, 
7.69, 7.872684992, 7.84, 7.64, 7.83, 7.71, 7.76, 7.851291827, 
7.73, 7.685, 7.96, 7.71, 7.62, 7.863, 7.872684992, 7.59, 7.81, 
7.87, 7.722932832, 7.77, 7.78, 7.84, 7.838, 7.74, 7.65, 7.66, 
7.67, 7.67, 7.680146501, 7.64, 7.8, 7.828, 7.67, 7.92, 7.615967003, 
7.82, 7.65, 7.74, 7.767, 7.68), Al2O3 = c(2, 2.01, 2.053, 1.88, 
2.03, 2.02, 2.01, 2.02, 2.01, 2.002830415, 2.02, 2.09, 1.9, 2.05, 
1.89, 2.021725042, 2.03, 2.044, 2.05, 1.96, 1.99, 2.041, 2.021725042, 
2, 2.01, 2.03, 1.983935789, 2.02, 1.88, 2.02, 2.038, 2.02, 2.09, 
2.01, 2.01, 2.02, 2.002830415, 2.03, 2.01, 2.008, 2, 2.03, 2.021725042, 
2.06, 1.88, 1.87, 2.02, 2.02)), row.names = c(NA, -48L), class = "data.frame")


我有以下代码

library(purr)

qqplots <- imap(df[-1], ~{
  ggplot(df[-1], aes(sample = .y)) + # Create QQplot with ggplot2 package
  ggtitle(paste0(.y, " Q-Q Plot")) +
  theme(plot.title = element_text(hjust = 0.5)) +
  ylab('Grade %')+
  stat_qq() +
  stat_qq_line(col = "red", lwd = 0.5)
  })

这会产生许多如下图

在此处输入图像描述

但我期待的是这样的 在此处输入图像描述

我究竟做错了什么?

标签: rdataframeggplot2

解决方案


您可以使用 :

library(ggplot2)

qqplots <- purrr::imap(df[-1], ~{
  ggplot(df, aes(sample = .data[[.y]])) + # Create QQplot with ggplot2 package
    ggtitle(paste0(.y, " Q-Q Plot")) +
    theme(plot.title = element_text(hjust = 0.5)) +
    ylab('Grade %')+
    stat_qq() +
    stat_qq_line(col = "red", lwd = 0.5)
})

或与lapply

qqplots <- lapply(names(df)[-1], function(x) {
  ggplot(df, aes(sample = .data[[x]])) + 
    ggtitle(paste0(x, " Q-Q Plot")) +
    theme(plot.title = element_text(hjust = 0.5)) +
    ylab('Grade %')+
    stat_qq() +
    stat_qq_line(col = "red", lwd = 0.5)
})

推荐阅读