Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
375 views
in Technique[技术] by (71.8m points)

r - how can I make stacked barplot with ggplot2

Hi I wanted to make a stacked barplot using ggplot2 with below data

Chr NonSyn_Snps Total_exonic_Snps
A01 9217    13725
A02 6226    9133
A03 14888   21531
A04 5272    7482
A05 4489    6608
A06 8298    12212
A07 6351    9368
A08 3737    5592
A09 12429   18119
A10 7165    10525

Basically i want to stack NonSyn_Snps and Total_exonic_Snps for each chromosome but unfortunately i cannot.

This is what i tried so far with no luck

ggplot(Chr.df_mod, aes(Chr, Total_exonic_Snps, fill = NonSyn_Snps)) + geom_bar(stat = "identity", colour = "white") + xlab("Chromosome") + ylab("Number of SNPs")

I am getting plot but not stacked one.

enter image description here

Can someone please help me troubleshoot this.

Thanks Upendra

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The ggplot idiom works best with long data rather than wide data. You need to melt your wide data frame into long format to benefit from many of ggplot's options.

# get data
dat <- read.table(text = "Chr NonSyn_Snps Total_exonic_Snps
A01 9217    13725
A02 6226    9133
                  A03 14888   21531
                  A04 5272    7482
                  A05 4489    6608
                  A06 8298    12212
                  A07 6351    9368
                  A08 3737    5592
                  A09 12429   18119
                  A10 7165    10525", header= TRUE)


# load libraries
require(ggplot2)
require(reshape2)

# melt data from wide to long
dat_m <- melt(dat)

# plot
ggplot(dat_m, aes(Chr, value, fill = variable)) + 
  geom_bar(stat = "identity") + 
  xlab("Chromosome") + 
  ylab("Number of SNPs")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...