2 Y轴直方图(正常频率与相对频率)

时间:2017-02-28 07:41:42

标签: r histogram

我想请你的帮助。

我分别有这2个情节。一个是正​​常频率,另一个是完全相同的数据,是相对频率。

你能告诉我如何在一个2轴(频率和相对频率?)的情节中加入它们吗?

x<- AAA$starch 
h<-hist(x, breaks=40, col="lightblue", xlab="Starch ~ Corn", 
    main="Histogram with Normal Curve", xlim=c(58,70),ylim = c(0,2500),axes=TRUE)
xfit<-seq(min(x),max(x),length=40) 
yfit<-dnorm(xfit,mean=mean(x),sd=sd(x)) 
yfit <- yfit*diff(h$mids[1:2])*length(x)
lines(xfit, yfit, col="blue", lwd=3)

frequency plot

library(HistogramTools)
x<- AAA$starch 
c <- hist(x,breaks=10, ylab="Relative Frequency", main="Histogram with Normal Curve",ylim=c(0,2500), xlim=c(58,70), axes=TRUE)
PlotRelativeFrequency((c))

relative frequency

谢谢!

编辑:

这只是我想要的一个示例图像......

2yaxisplot

1 个答案:

答案 0 :(得分:1)

我使用package latticeExtra中的doubleYScale。

这是一个例子(我不确定相对频率计算):

library(latticeExtra)

set.seed(42)
firstSet <- rnorm(500,4)

breaks = 0:10

#Cut data into sections
firstSet.cut = cut(firstSet, breaks, right=FALSE)
firstSet.freq = table(firstSet.cut) 

#Calculate relative frequency
firstSet.relfreq = firstSet.freq / length(firstSet) 

#Parse to a list to use xyplot later and assigning x values
firstSet.list <- list(x = 1:10, y = as.vector(firstSet.relfreq))

#Build histogram and relative frequency curve
hist1 <- histogram(firstSet, breaks = 10, freq = TRUE, col='skyblue', xlab="Starch ~ Corn", ylab="Frequency", main="Histogram with Normal Curve", ylim=c(0,40), xlim=c(0,10), plot=FALSE)
relFreqCurve <- xyplot(y ~ x, firstSet.list, type="l", ylab = "Relative frequency", ylim=c(0,1))

#Build double objects plot
doubleYScale(hist1, relFreqCurve, add.ylab2 = TRUE)

这是两个y轴具有不同比例的结果:

Frequency histogram and relative frequency curve