0
votes

I would like to make two different histograms with a distribution curve in the same window with "data1" and "data2" from a txt file. I can create a histogram with data from columns of "data1" and "data2" combined but not seperated. How can I seperate my data? Thanks.

data1  data2
155      130
195      10
21       26
15       210
190      15
2        205
182      50
115      55
170      1
17       56

Data = as.matrix( read.table( "c:\\Data.txt",header=TRUE ) )
attach( Data )

par( mfrow=c(1,2) ) #c(rows,columns)

hist(Data ,plot=TRUE, col=c("red","blue"),
     main = "Histogram of Data1",
     xlab="X-Axis", ylab="Y-Axis", cex.lab= 1, col.lab="blue" )

#Curve is not working even if data is combined
curve(dnorm(x, mean=mean(Data), sd=sd(Data)), add=TRUE, col="blue", lwd=2)
2
It gives error : Error in Data$data1 : $ operator is invalid for atomic vectors hist(Data$data1,plot=TRUE, col=c("red","blue"), main = "Histogram of Data1", xlab="X-Axis", ylab="Y-Axis", cex.lab= 1, col.lab="blue", prob=TRUE ) - 2 X

2 Answers

0
votes

Or try this:

Data <- structure(list(data1 = c(155, 195, 21, 15, 190, 2, 182, 115, 
                                 170, 17), data2 = c(130, 10, 26, 210, 15, 205, 50, 55, 1, 56)), .Names = c("data1", 
                                                                                                            "data2"), row.names = c(NA, -10L), class = "data.frame")
par( mfrow=c(1,2) ) 
invisible(lapply(1:ncol(Data), function(i){
  x <- Data[,i]
  h <- hist(x, col=c("red","blue"),
            main = paste0("Histogram of ", names(Data)[i]),
            xlab="X-Axis", ylab="Y-Axis", breaks=5,
            cex.lab= 1, col.lab="blue")
  xfit<-seq(min(x),ceiling(210/50)*50,length=40) 
  yfit<-dnorm(xfit,mean=mean(x),sd=sd(x)) 
  yfit <- yfit*diff(h$mids[1:2])*length(x) 
  lines(xfit, yfit, col="green", lwd=2)
}))

(source) enter image description here

0
votes

Try this

par( mfrow=c(1,2) ) 
invisible(lapply(1:ncol(Data), function(i){
  x <- Data[,i]
  hist(x, col=c("red","blue"),
       main = paste0("Histogram of ", names(Data)[i]),
       xlab="X-Axis", ylab="Y-Axis", 
       cex.lab= 1, col.lab="blue",
       prob=TRUE)

  curve(dnorm(x, mean=mean(x), sd=sd(x)), 
        add=TRUE, col="blue", lwd=2)

}))

par( mfrow=c(1,1))

enter image description here