I am having a perplexing problem trying to use facet_wrap in ggplot, with both my real dataset and a simplified dummy dataset. I am trying to plot heterozygosity across the genome for multiple individuals, with each chromosome shown separately.
My dummy data:
chr1 123000 124000 2 0.00002 26 0.00026 indiv1
chr1 124000 125000 3 0.00003 12 0.00012 indiv1
chr1 125000 126000 1 0.00001 6 0.00006 indiv1
chr1 126000 126000 2 0.00002 14 0.00014 indiv1
chr2 123000 124000 6 0.00006 20 0.00020 indiv1
chr2 124000 125000 0 0.00000 12 0.00012 indiv1
chr1 123000 124000 2 0.00002 26 0.00026 indiv2
chr1 124000 125000 3 0.00003 12 0.00012 indiv2
chr1 125000 126000 1 0.00001 6 0.00006 indiv2
chr1 126000 126000 2 0.00002 14 0.00014 indiv2
chr2 123000 124000 6 0.00006 20 0.00020 indiv2
chr2 124000 125000 0 0.00000 12 0.00012 indiv2
My code to read in the data:
hetshoms <- read.table("fakedata.txt", header=F)
chrom <- hetshoms$V1
start.pos <- hetshoms$V2
end.pos <- hetshoms$V3
hets <- hetshoms$V4
het_stat <- hetshoms$V5
homs <- hetshoms$V6
hom_stat <- hetshoms$V7
indiv <- hetshoms$V8
HetRatio <- hets/(hets+homs)
When I try to plot the chromosomes separately in qplot, it works fine:
testplot <- qplot(start.pos, HetRatio, facets = chrom ~ ., colour=chrom)
But when I try an analogous thing in ggplot, it does not work. The first part works fine:
testplot <- ggplot(hetshoms, aes(x=start.pos, y=HetRatio)) + geom_point(aes(color=chrom))
but when I try to add the facet_wrap:
testplot + facet_wrap(~chrom)
This produces the following error
"Error en layout_base(data, vars, drop = drop) : At least one layer must contain all variables used for facetting"
I have tried adding an (as.formula(paste)) to facet_wrap() and directly calling hetshoms$V1 but neither solves the problem.
I would appreciate any suggestions for how to correct my code.
To replicate qplot
output we need facet_grid(chrom~.)
#data
hetshoms <- read.table(text="
chr1 123000 124000 2 0.00002 26 0.00026 indiv1
chr1 124000 125000 3 0.00003 12 0.00012 indiv1
chr1 125000 126000 1 0.00001 6 0.00006 indiv1
chr1 126000 126000 2 0.00002 14 0.00014 indiv1
chr2 123000 124000 6 0.00006 20 0.00020 indiv1
chr2 124000 125000 0 0.00000 12 0.00012 indiv1
chr1 123000 124000 2 0.00002 26 0.00026 indiv2
chr1 124000 125000 3 0.00003 12 0.00012 indiv2
chr1 125000 126000 1 0.00001 6 0.00006 indiv2
chr1 126000 126000 2 0.00002 14 0.00014 indiv2
chr2 123000 124000 6 0.00006 20 0.00020 indiv2
chr2 124000 125000 0 0.00000 12 0.00012 indiv2
",header=FALSE)
#calculate HetRatio
colnames(hetshoms) <- c("chrom","start.pos","end.pos","hets","hets_stat","homs","homs_stat","indiv")
hetshoms$HetRatio <- hetshoms$hets/(hetshoms$hets+hetshoms$homs)
#plot
ggplot(hetshoms, aes(x=start.pos, y=HetRatio)) +
geom_point(aes(color=chrom)) +
facet_grid(chrom~.)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.