首页 文章

生成每列一个条形的条形图(将列转换为组)

提问于
浏览
0

我正在尝试从此测试数据集(practice_dataset.csv)生成R中的图表:

genes,cell1,cell2,cell3,cell4
gene1,14,10,20,3
gene2,12,5,3,0
gene3,8.5,3,5,0
gene4,13,0,0,0
gene5,2.5,7.5,1,10

我想显示每个细胞存在多少基因(gene1-gene5)的数量,其值大于0 . 我正在使用colSums(data> 0)来汇总列,但我不明白如何告诉R每列是一个组 . 这就是我的代码目前的样子:

setwd("~/.../...")

library(ggplot2)

pdf("testplot.pdf", w=20, h=7)

#Load dataset
data <- read.table("practice_dataset.csv",
                   sep=",",
                   header=TRUE)

# Summarize the number of genes with a value of >0 for each column
genes.no <- colSums(data > 0)

# Generate bar plot with one bar of genes.no per cell/column 
geom_bar(genes.no)

dev.off()

1 回答

  • 0

    我们可以从 base R 使用 barplot . 如果'genes'是第一列,我们需要在执行 colSums 时删除该列,因为它是非数字的( data[-1] ) . 并做 barplot .

    barplot(colSums(data[-1] >0))
    

    enter image description here


    如果我们想用 ggplot 执行此操作,我们可以将'wide'格式转换为'long'并使用 gather (来自 tidyr ),将 sum 的'Val'分组为'Var'并使用 ggplot 语法获取条形图 .

    library(ggplot2)
    library(tidyr)
    library(dplyr)
    gather(data, Var, Val, -genes)  %>%
              group_by(Var) %>% 
              summarise(Val= sum(Val>0)) %>% 
              ggplot(., aes(x=Var, y=Val)) +
                      geom_bar(stat="identity")
    

相关问题