r - 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 视图节点内运行。
解决方案
推荐阅读
- javascript - 移动设备上按钮的可点击区域错误
- html - 数据表 - dataTables_length、dataTables_filter、dataTables_info 和 dataTables_paginate 都显示在单独的行问题
- python - 将多种格式日期转换为仅一种
- scikit-learn - Scikit Spectral Clustering 无法对同心圆进行分类
- javascript - 如何在每毫秒滴答的 onTick 事件中设置状态
- reactjs - 组件和自定义钩子有什么区别?
- python - 用于查找覆盖字符串区域的最少 k-mer 的快速算法
- javascript - 如何制作一个匿名的 DM Discord 机器人,该机器人将仅在指定频道或图像和文件中发布图像,然后确认它已收到
- c++ - LeetCode 问题。两个 Sum 链表版本 C++
- android - 在导入错误后更新 Android 中的 OneSignal 依赖项