3

I want to plot a histogram of lengths based on locations. I am trying to overlay the histogram where data of one location is one color and the other location is a different color.

Here is the R code I have so far that just plots the histogram:

    fasta<-read.csv('fastadata.csv',header = T)
    norton<-fasta[fasta$SampleID == ">P.SC1Norton-28F",]
    cod<-fasta[fasta$SampleID == ">P.SC4CapeCod-28F ",]
    bins <- seq(200, 700, by=25)
    hist(fasta[,3], breaks=bins, main="Histogram of ReadLengths of a set bin size for Cape Cod and Norton", xlab="ReadLengths")

I keep seeing ggplot used, but I am unsure how to use this function within one table and using the binning I used.

Output of dput(head(fasta)):

structure(list(SampleID = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c(">P.SC1Norton-28F",">P.SC4CapeCod-28F"), class = "factor"), SeqName = structure(c(5674L, 5895L, 5731L, 5510L, 4461L, 5648L), .Label = c("IJO4WN203F00DQ", "IKTXKCP03HKQ5E"), class = "factor"), ReadLength = c(394L, 429L, 437L, 438L, 459L, 413L)), .Names = c("SampleID", "SeqName", "ReadLength"), row.names = c(NA, 6L), class = "data.frame")
Thomas
  • 42,067
  • 12
  • 102
  • 136
user3018479
  • 135
  • 2
  • 8

2 Answers2

8

Since you mentioned ggplot, you have several options.

# make up some data
set.seed(1)
sampleID <- c(">P.SC1Norton-28F",">P.SC4CapeCod-28F")
df <- data.frame(SampleID=rep(sampleID,each=500),
                 ReadLength=round(c(rnorm(500,350,100),rnorm(500,450,100))))

library(ggplot2)
ggplot(df) +
  geom_histogram(aes(x=ReadLength, fill=SampleID), 
                 colour="grey50", alpha=0.5, position="identity")

ggplot(df) +
  geom_histogram(aes(x=ReadLength, fill=SampleID), position="dodge")

ggplot(df) +
  geom_histogram(aes(x=ReadLength, fill=SampleID))+
  facet_wrap(~SampleID,nrow=2)

jlhoward
  • 56,091
  • 6
  • 91
  • 135
7

Use the add=TRUE parameter in a second call to hist. Also, using an alpha-transparent color will probably help.

hist(norton[,3], breaks=bins, main="Histogram of ReadLengths of a set bin size for Cape Cod and Norton", 
     xlab="ReadLengths", col=rgb(1,0,0,.5), border=NA)
hist(cod[,3], breaks=bins, col=rgb(0,0,1,.5), add=TRUE, border=NA)

Here's an update using @jlhoward's data. Note that the axis labels and headings are messy by default:

layout(1:2)
hist(df$ReadLength[df$SampleID==levels(df$SampleID)[1]],
     col=rgb(1,0,0,.5), border=NA)
hist(df$ReadLength[df$SampleID==levels(df$SampleID)[2]],
     col=rgb(0,0,1,.5), border=NA, add=TRUE)

enter image description here

hist(df$ReadLength[df$SampleID==levels(df$SampleID)[1]],
     col=rgb(1,0,0,.5), border=NA)
hist(df$ReadLength[df$SampleID==levels(df$SampleID)[2]],
     col=rgb(0,0,1,.5), border=NA)

enter image description here

Thomas
  • 42,067
  • 12
  • 102
  • 136