在R中的一页上重叠直方图

时间:2017-08-31 13:22:18

标签: r histogram

我是R的初学者。我设法将我的数据绘制成重叠的直方图。但是,我想将所有直方图放在一页上。我正在努力,因为我无法告诉R,哪一组可以选择(只设法绘制其中一个图)。

这是代码:

        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)

基本上,我得到两个单独的重叠直方图,但不能将它们放在同一页面上。

1 个答案:

答案 0 :(得分:1)

编辑:我显然没有彻底阅读你的问题。我看到你想出了add = T。

我认为你正在寻找的是我先做的评论:

par(mfrow = c(a,b))其中a和b是您希望打印图形对象的行数和列数。我用这张照片的c(2,2)。

enter image description here

我发了评论,但听起来你可能在谈论add = T选项。

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

您可以使用颜色的透明度选项来查看两者的重叠。如rgb(1,0,0,1 / 4)为颜色。

enter image description here

透明色:

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