Overlapping overlay in R

I have the following code in R.

x = c(rep(2,10),rep(4,10)) y1 = c(5.1,3,4.2,4.1,4.8,4.0,5,4.15,3,4.5) y2 = c(9.1,8,9.2,8.2,7,9.5,8.8,9.3,10,10.4) y = c(y1,y2) plot(x,y,pch=16,cex=0.9,xlim=c(0,6),ylim=c(0,13)) 

This code creates a graph with two stripes of dots. I superimposed normal curves to the side on these stripes using powerpoint. How can I do this in R (drawing side normal curves) using actual values ​​and sd values? NOTE : I repeat, normal curves are not part of the graph. The code above just creates a raw chart.

enter image description here

+4
source share
1 answer

First calculate the mean and standard deviation for y1 and y2 .

 m1<-mean(y1) s1<-sd(y1) m2<-mean(y2) s2<-sd(y2) 

Then he made two data frames (for convenience) that contain y values ​​as a sequence of numbers (wider than the actual values ​​of y1 and y2 ). Then calculated density values ​​for x using dnorm() and calculated mean and standard deviation values. Then add 2 or 4 to shift the values ​​to the desired position.

 df1<-data.frame(yval=seq(1,7,0.1),xval=(dnorm(seq(1,7,0.1),m1,s1)+2)) df2<-data.frame(yval=seq(6,12,0.1),xval=(dnorm(seq(6,12,0.1),m2,s2)+4)) 

Added density lines() with the lines() function.

 plot(x,y,pch=16,cex=0.9,xlim=c(0,6),ylim=c(0,13)) with(df1,lines(xval,yval)) with(df2,lines(xval,yval)) 

enter image description here

+7
source

All Articles