首页 > 解决方案 > ggplot2 面板在 for 循环中填充了错误的值

问题描述

我想使用嵌套的 for 循环、ggplot2 和 grid.arrange 创建一个散点图矩阵。循环遍历列以创建不同的子图。这显然有效,因为每个地块的子图实验室都不同。但是,每个子图的绘图轴和面板都是相同的。现在变得有趣了:使用的列是 i = j = 4 的情况,甚至在 if-else 的不同分支中。

我的第一次尝试是使用 rlang 的 duplicate() 函数强制进行深层复制。
我发现的唯一其他提示是明确使用 print() 来显示绘图。请参阅: https
://cran.r-project.org/doc/FAQ/R-FAQ.html#Why-do-lattice_002ftrellis-graphics-not-work_003f 这两个选项都没有改变最终情节中的任何内容。
删除 if-else 内容以始终生成 i<j 分支会产生“相同”的图。手动创建 16 个图(硬编码,没有循环)会产生所需的行为。

代码示例:

library(tidyverse)
library(rlang)
library(egg)

#species is in last column
n = ncol(iris) - 1
plot_list = list()

for (i in 1:n) {
  for (j in 1:n) {
    #diagonal
    if (i==j) {
      new_plot = ggplot() + annotate("text", x = 4, y = 25, size = 5, label = colnames(iris)[i]) + theme_void()
    }
    #upper triangle
    else if (i < j) {
      #assign to new plot nested into a print(), doesn't help
      new_plot = print(
        ggplot() +
        geom_point(aes(x = iris[,j], y = iris[,i], colour=iris[,5]), shape=18, size=3.5) +
        labs(x = colnames(iris)[j], y = colnames(iris)[i]) +
        theme_light() +
        theme(legend.position="none")
      )
    }
    #lower triangle
    else {
      new_plot = ggplot() + annotate("text", x = 4, y = 25, size = 5, label = "lower triangle") + theme_void()
    }

    #this doesn't help
    print(new_plot)
    #this doesn't help either
    plot_buffer = duplicate(new_plot, shallow=FALSE)
    #append new plot to plot list
    plot_list = append(plot_list, list(plot_buffer))
  }
}

grid.arrange(grobs = plot_list, top = "grand title")

这是错误的情节。Petal.Width 用作 x 和 y 值列 everythyme: 错误的情节

PS:我只使用 R 来可视化我的数据,所以我的知识重点是 ggplot2。此代码在 KNIME 的 R 视图节点内运行。

标签: rggplot2

解决方案


你可以aes_string这样使用:

ggplot(iris) +
  geom_point(aes_string(colnames(iris)[j], colnames(iris)[i], color = "Species"), shape=18, size=3.5) +
  theme_light() +
  theme(legend.position="none")

这也确保您不必再使用labs()

这给

在此处输入图像描述


推荐阅读