简体   繁体   English

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

[英]How do I use for loops and data within a matrix to create a points plot within R?

I have a question involving for loops and a points plot.我有一个涉及 for 循环和点图的问题。

I have to use the measurements table (see below) to create a plot (see picture).我必须使用测量表(见下文)来创建一个图(见图)。 My question is how do I use the for loops to obtain the plot?我的问题是如何使用 for 循环来获取绘图? I tried creating an empty plot which can be used to put the data into but don't know whether this was the best way to go about completing the task.我尝试创建一个可用于将数据放入的空图,但不知道这是否是完成任务的最佳方式。 I am very new to R so am not very experienced with for loops etc.我对R很陌生,所以对 for 循环等不是很有经验。

Here's an example这是一个例子

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)

在此处输入图片说明

DATA数据

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"
))

Here is some ggplot2 code which makes a similar plot这是一些 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM