我在R和编程方面是新手,所以我不知道如何在这个网站上很好地解释它,但我找不到更好的论坛来询问。
基本上,我有一个6x6矩阵,每行是一个离散的基因,每列是一个样本。
我想让基因作为x轴,y轴是样本的值,这样每个基因就会有6个以上的样本在各自的值上。
我在Excel中有这个矩阵,当我突出显示它并绘制它时,它正好给出了我想要的结果。
但尝试在R中复制它,最多只能得到一个巨大的格子图。
我尝试过boxplot()
、scatterchart()
、plot()
和ggplot()
。
我假设我必须改变我的矩阵,但我不知道怎么做。
发布于 2019-06-19 06:48:06
这可能会有所帮助:
library(tidyverse)
gene <- c("a", "b", "c", "d", "e", "f")
x1 <- c(1,2,3,4,5,6)
x2 <- c(2,3,4,5,-6,7)
x3 <- c(3,4,5,6,7,8)
x4 <- c(4,-5,6,7,8,9)
x5 <- c(9,8,7,6,5,4)
x6 <- c(5,4,3,2,-1,0)
df <- data.frame(gene, x1, x2, x3, x4, x5, x6) #creates data.frame
as_tibble(df) # convenient way to check data.frame values and column format types
df <- df %>% gather(sample, observation, 2:7) # here's the conversion to long format
as_tibble(df) #watch df change
#example plots
p1 <- ggplot(df, aes(x = gene, y = observation, color = sample)) + geom_point()
p1
p2 <- ggplot(df, aes(x = gene, y = observation, group = sample, color = sample)) +
geom_line()
p2
p3 <- p2 + geom_point()
p3
发布于 2019-06-19 07:35:46
这很容易解决-如果你的矩阵是6x6,每行一个基因,每列一个观察值(因此每个基因有六个观察值),你首先需要将其设置为长格式(36行)-对于这样一个简单的格式,这可以使用unlist
来完成-然后将其与用于表示基因的数字向量进行绘制:
# Here I make some dummy data - a 6x6 matrix of random numbers:
df1 <- matrix(rnorm(36,0,1), ncol = 6)
# To help show which way the data unlists, and make the
# genes different, I add 4 to gene 1:
df1[1,] <- df1[1,] + 4
#### TL;DR - HERE IS THE SOULTION ####
# Then plot it, using rep to make the x-axis data vector
plot(x = rep(1:6, times = 6), y = unlist(df1))
要提高可读性,请添加轴标签:
# With axis labels
plot(x = rep(1:6, times = 6), y = unlist(df1),
xlab = 'Gene', ylab = 'Value')
您还可以将ggplot
与geom_point
美学或geom_jitter
一起使用-例如:
ggplot() +
geom_jitter(mapping = aes(x = rep(1:6, times = 6), y = as.numeric(unlist(data.frame(df1)))))
请注意,您还可以在基数R中使用rnorm()
对x值创建“抖动”效果,并使用rnorm()
函数的最后一个参数调整抖动量:
plot(x = rep(1:6, times = 6) + rnorm(36, 0, 0.05), y = unlist(df1), xlab = 'Gene', ylab = 'Value')
https://stackoverflow.com/questions/56657803
复制相似问题