Orbis
Orbis

Reputation: 15

Overlapping histograms on one page in R

I am a beginner with R. I managed to plot my data into overlapping histograms. However, I would like to place all the histograms on one page. I am struggling as I am not able to tell R, which sets to pick (only manage to plot one of the plots).

This is the code:

        df<-read.csv("Salt dshalo sizes.csv",header=T)
    #View(df)

    library(ggplot2)

    DSA<-df[,1]
    DS1<-df[,2]
    DSB<-df[,5]
    DS2<-df[,6]
    DSC<-df[,9]
    DS3<-df[,10]

    #remove the NA column by columns separately or it will chop the data
    DSA=na.omit(DSA)
    DS1=na.omit(DS1)
    DSB=na.omit(DSB)
    DS2=na.omit(DS2)
    DSC=na.omit(DSC)
    DS3=na.omit(DS3)


    #plot histograms for DSA, DSB and DSC on one same graph 
    hist(DSA, prob=TRUE, main="Controls", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
    hist(DSB, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
    hist(DSC, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
    #add a legend to the histogram 
    legend("topright", c("Control 1", "Control2", "Control3"), text.width=c(1,1,1),lwd=c(2,2,2), 
           col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
    box()

 #plot histograms for DS1, DS2 and DS3 on one same graph 
    hist(DS1, prob=TRUE, main="Monoculture Stressed", xlab="Sizes (um)", ylab="Frequency", col="yellowgreen",xlim= c(5,25), ylim=c(0,0.5), breaks=10)
    hist(DS2, prob=TRUE, col=rgb(0,0,1,0.5),add=T)
    hist(DS3, prob=TRUE, col=rgb(0.8,0,1,0.5),add=T)
    #add a legend to the histogram 
    legend("topright", c("DS1", "DS2", "DS3"), text.width=c(1,1,1),lwd=c(2,2,2), 
           col=c(col="yellowgreen", col="blue", col="pink",cex= 1))
    box()

# put both overlapping histograms onto one page
    combined <- par(mfrow=c(1, 2))
    plot(hist(DSA),main="Controls")
    plot(hist(DS1),main="Monoculture stressed")
    par(combined)

Basically, I get two separate overlapping histograms, but cannot put them on the same page.

Upvotes: 0

Views: 4061

Answers (1)

akaDrHouse
akaDrHouse

Reputation: 2250

EDIT: I evidently didn't read your question thoroughly. I see you figured out the add =T.

I assume what you are looking for then is the comment I made first:

par(mfrow = c(a,b)) where a and b are the number of rows and columns you want the graphics objects to be printed. I used c(2,2) for this pic.

enter image description here

I made a comment, but sounds like you may be talking about the add=T option.

a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col="yellow")
hist(b, add=T, col="purple" )

you can play around with transparency options on colors to see both overlap. Such as rgb(1,0,0,1/4) as the color.

enter image description here

With transparency colors:

a=rnorm(100, 2, 1)
b=rnorm(100, 4, 1)
hist(a, xlim=c(0,10), col=rgb(1,1,0,1/4))
hist(b, add=T, col=rgb(1,0,0,1/4) )

enter image description here

Upvotes: 4

Related Questions