我对R还是很陌生,所以请问一个菜鸟问题。 我有一个看起来像这样的数据框:
gene ctrl treated
gene_1 100 37.5
gene_2 100 20.2
... ... ...
对于df中的每一行(即每个基因),我想以这样的方式绘制这些值,即ctrl和待遇是彼此相邻的。 下面的代码提供了一些接近我想要的东西,但是输出并未按应有的方式进行分组:将控件的条形绘制在处理过的样品之前。
barplot(height = df$df.ctrl1, df$df.avg_treated), names.arg = df$df.gene)
我知道有很多类似的问题,但是我没有成功解决它们。 有人可以帮助我了解我在做什么错吗?
第二个(可选)问题:如果我想根据基因ID对条进行颜色编码怎么办?
非常感谢。
答案 0 :(得分:1)
我会为此使用ggplot。让我们从一个稍微扩展的示例开始:
df <- data.frame(genes = c("gene_1", "gene_2", "gene_3", "gene_4"),
ctrl = c(50, 60, 70, 80),
treated = c(55, 64, 75, 83))
df
#> genes ctrl treated
#> 1 gene_1 50 55
#> 2 gene_2 60 64
#> 3 gene_3 70 75
#> 4 gene_4 80 83
我们要做的第一件事是使用tidyr::pivot_longer
将数据框切换为长格式,以将所有值放在一列中,并将“ ctrl”和“处理”的标签放在另一列中。然后我们可以使用ggplot构建输出:
library(tidyr)
library(ggplot2)
df %>%
pivot_longer(cols = c("ctrl", "treated")) %>%
ggplot(aes(name, value, fill = genes, alpha = name)) +
geom_col(position = position_dodge(), color = "black") +
scale_alpha_manual(values = c(0.5, 1), guide = guide_none()) +
facet_grid(~genes, scales = "free_x", switch = "x") +
theme(strip.placement = "outside",
panel.spacing = unit(0, "points"),
strip.background = element_blank(),
strip.text = element_text(face = "bold", size = 12)) +
labs(x = "Gene")
由reprex package(v0.3.0)于2020-08-22创建
答案 1 :(得分:1)
请考虑转置数据,并用dimnames
转换为矩阵。然后使用barplot
运行legend
。下面用随机数据演示。注意:ylim
已针对漂亮的范围限制进行了调整。
set.seed(92220)
df <- data.frame(gene = paste("gene", 1:30),
ctrl = runif(30, 50, 100),
treated = runif(30, 50, 100))
head(df)
# gene ctrl treated
# 1 gene 1 75.74607 76.15832
# 2 gene 2 61.73860 70.19874
# 3 gene 3 56.57906 63.67602
# 4 gene 4 60.23045 80.21108
# 5 gene 5 62.52773 60.86909
# 6 gene 6 85.71849 61.25974
# TRANSPOSE INTO MATRIX WITH DIMNAMES
dat <- `dimnames<-`(t(as.matrix(df[c("ctrl", "treated")])),
list(c("ctrl", "treated"), df$gene))
barplot(dat, beside=TRUE, col=c("blue", "red"), las=3,
main="Control Vs. Treatment",
ylim=range(pretty(c(0, dat*1.05))))
legend("top", legend=row.names(dat),
fill=c("blue", "red"), ncol=2, cex=0.75)