我可以像这样结合密度和频率图
hist(ex, col="red", prob=TRUE) lines(density(ex), col="red")但也有可能在每一侧都有两个轴? 举个例子:
更新:取决于实际数据的解决方案:
#margin from right par(mar=c(5, 4, 4, 4) + 0.1) hist(ex, col="red", prob=TRUE) lines(density(ex), col="red") # axis ticks axis(4, at=seq(0,0.4,0.1)*50, labels=seq(0,0.4,0.1)*2500) # axis label mtext("Frequency", side=4, line=3)I can combine both density and frequency plots like this
hist(ex, col="red", prob=TRUE) lines(density(ex), col="red")But it possible to also have both axises on each side? Just an example:
UPDATED: solution that depends on the actual data:
#margin from right par(mar=c(5, 4, 4, 4) + 0.1) hist(ex, col="red", prob=TRUE) lines(density(ex), col="red") # axis ticks axis(4, at=seq(0,0.4,0.1)*50, labels=seq(0,0.4,0.1)*2500) # axis label mtext("Frequency", side=4, line=3)最满意答案
重新评论:这里是一个使用基数R的公式快速 - 基于上面的代码 - 您不必手动定义轴。 显而易见的困难是密度或频率不是漂亮的/圆形的数字(如果你想要它们都是圆的那么蜱可能会在不同的地方)。 我认为以规定的间隔保持密度更为明智。 这也需要不断的休息。
对于绘图我将密度分配给LHS轴,但这很容易调整。
histfreq <- function(X, lines=TRUE, ...) { par(mar=c(5, 4, 4, 4) + 0.1) h <- hist(X, plot=FALSE) n.obs <- length(na.omit(X)) d <- density(na.omit(X)) h <- hist(X, prob=TRUE, yaxt="n",ylim = c(0,max(h$density,d$y)*1.1),...) # axis ticks and labels # y axis(2, at = pretty(c(0,h$density)), labels = formatC( pretty(c(0,h$density)), digits = 1, format = "f")) # 2nd y axis(4, at = pretty(c(0,h$density)), labels = formatC(signif(pretty(c(0,h$density)) * n.obs * unique(diff(h$breaks)), digits = 2), digits=0, format = "f")) mtext("Frequency" , side=4, line=3) if (lines) lines(d, ...) } # Call plot histfreq(rnorm(57), col="red")Re your comment: here is a quick go at a formula using base R - based on your code above - where you will not have to manually define the axes. The obvious difficulty is either the density or the frequency wont be pretty/round numbers (if you want them to both be round then the ticks will likely be at different places). I think it is more sensible to to have the density at defined intervals. Also this requires constant breaks.
For the plot i assign the density to the LHS axis but this will be easy enough to tweak.
histfreq <- function(X, lines=TRUE, ...) { par(mar=c(5, 4, 4, 4) + 0.1) h <- hist(X, plot=FALSE) n.obs <- length(na.omit(X)) d <- density(na.omit(X)) h <- hist(X, prob=TRUE, yaxt="n",ylim = c(0,max(h$density,d$y)*1.1),...) # axis ticks and labels # y axis(2, at = pretty(c(0,h$density)), labels = formatC( pretty(c(0,h$density)), digits = 1, format = "f")) # 2nd y axis(4, at = pretty(c(0,h$density)), labels = formatC(signif(pretty(c(0,h$density)) * n.obs * unique(diff(h$breaks)), digits = 2), digits=0, format = "f")) mtext("Frequency" , side=4, line=3) if (lines) lines(d, ...) } # Call plot histfreq(rnorm(57), col="red")更多推荐
发布评论