在R中同时具有频率轴和密度轴的直方图

在R中同时具有频率轴和密度轴的直方图,r,R,我可以像这样组合密度和频率图 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=&

我可以像这样组合密度和频率图

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)

回复您的意见:这里是一个使用base 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")

histfreq看看这个。动态解决方案会更好,但你的也可以。谢谢!