如何在矩阵内使用for循环和数据在R中创建点图?

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在矩阵内使用for循环和数据在R中创建点图?相关的知识,希望对你有一定的参考价值。

我有一个涉及循环和点图的问题。

我必须使用测量表(见下文)来创建一个图(见图)。我的问题是如何使用for循环来获取情节?我尝试创建一个空图,可用于输入数据,但不知道这是否是完成任务的最佳方式。我是R的新手所以对于循环等不是很有经验。

答案

这是一个例子

graphics.off()

windows(width = 10, height = 5)
#Empty Plot
plot(x = 1, y = 1, type = "n",
     xlim = c(1, NCOL(measurements)),
     ylim = c(min(measurements), max(measurements)),
     xlab = "Gene", ylab = "Value",
     axes = FALSE)   

#Add boxes and axis-labels
box()
axis(1, at = 1:NCOL(measurements), labels = colnames(measurements))
axis(2)

#Add points
for(i in 1:NCOL(measurements)){
    points(cbind(i, measurements[,i]),
           pch = 22, col = as.numeric(as.factor(row.names(measurements))))
}

#enable drawing outside plot region
par(xpd = TRUE)

#Add legend
legend("top", inset = c(0, -0.2), legend = row.names(measurements),
       fill = NA, border = NA,
       pch = 22, col = as.numeric(as.factor(row.names(measurements))),
       ncol = NROW(measurements), cex = 0.8)

enter image description here

数据

measurements = structure(list(Kc167_1 = c(10L, 10L, 61L, 20L, 89L, 72L, 55L, 
62L, 70L, 89L), Kc167_2 = c(9L, 56L, 5L, 86L, 20L, 69L, 75L, 
27L, 75L, 99L), Kc167_3 = c(3L, 8L, 28L, 89L, 70L, 82L, 86L, 
26L, 76L, 74L), BG3_1 = c(47L, 3L, 98L, 53L, 84L, 53L, 8L, 18L, 
86L, 95L), BG3_2 = c(5L, 34L, 83L, 68L, 91L, 15L, 97L, 10L, 1L, 
6L), BG3_3 = c(93L, 1L, 57L, 87L, 70L, 84L, 14L, 59L, 61L, 25L
), S2_1 = c(55L, 54L, 83L, 38L, 42L, 5L, 1L, 95L, 72L, 33L), 
    S2_2 = c(74L, 85L, 83L, 74L, 1L, 73L, 67L, 6L, 22L, 24L), 
    S2_3 = c(96L, 18L, 80L, 79L, 6L, 8L, 84L, 63L, 34L, 27L)), .Names = c("Kc167_1", 
"Kc167_2", "Kc167_3", "BG3_1", "BG3_2", "BG3_3", "S2_1", "S2_2", 
"S2_3"), class = "data.frame", row.names = c("Clic", "Treh", 
"bib", "CalpC", "tud", "cort", "S2P", "Mitofilin", "Oxp", "Ada1-2"
))
另一答案

这是一些ggplot2代码,它可以生成类似的图

library(tidyverse)
measurements %>% 
  rownames_to_column(var = "gene") %>% 
  gather(key = key, value = value, -gene) %>% 
  ggplot(aes(x = gene, y = value, colour = key)) + 
  geom_point() +
  labs(x = "Gene", y = "Expression Level", title = "Expression Level") +
  theme(axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5))

以上是关于如何在矩阵内使用for循环和数据在R中创建点图?的主要内容,如果未能解决你的问题,请参考以下文章

将屏幕空间转换为世界空间以在 python 中创建点云

在 Python 中创建点类

MATLAB中如何用for 循环将结果代入矩阵中?

如何将来自for循环的数据存储在for循环内? (r中的滚动相关)

循环在R中创建几个矩阵(可能使用粘贴)

2018-10-31用R绘制散点图矩阵(成对的散点图)