【问题标题】:Integrating histogram and density curve, with one axis for frequency and the other for density整合直方图和密度曲线,一轴表示频率,另一轴表示密度
【发布时间】:2016-07-24 22:59:05
【问题描述】:

我正在使用hist()lines() 函数创建带有密度叠加的直方图,并希望有一个显示频率而不是密度的y-axis

有什么方法可以使用hist() 而不使用ggplot?将频率轴作为右侧的第二个 y 轴会更好。这是我的代码:

g <- rnorm(2000,5,1)
h<-hist(g, breaks=50, col="bisque",     
        border="black",ylab="Frequeny",yaxt='n',
        main="Title",xlab=paste0("Cr","(mg/dL)"),prob=TRUE) 
Axis(side=2, at=seq(0, 200, by=20))
lines(density(g),col="dimgray") #For Overlay

设置prob = FALSE 没有帮助,因为那时线条不适用于密度叠加。

【问题讨论】:

    标签: r plot histogram


    【解决方案1】:

    我们先生成数据和hist对象:

    set.seed(0)  ## added for reproducibility
    g <- rnorm(2000, 5, 1)
    h <- hist(g, breaks = 50, plot = FALSE)
    

    我暂时抑制了plot = FALSE 的绘图。

    问题是,我们想要两个 y 轴:

    • 左侧显示计数/频率;
    • 右侧显示密度。

    基本上我们在两个轴上的密度值处添加刻度线,但是

    • 在左侧显示相应的计数/频率;
    • 在右侧显示密度值。

    hist 对象中的密度值为h$density。对于漂亮的图表,我们申请 pretty() 获取刻度线位置:

    pos <- pretty(h$density, n = 5)
    # [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6
    

    要在pos 找到相应的计数,我们这样做:

    freq <- round(pos * length(g) * with(h, breaks[2] - breaks[1]))
    # [1]   0  20  40  60  80 100 120
    

    这里使用的round()只是为了确保丢弃有限精度计算引入的数字,以便我们以整数结束。

    现在我们已准备好生成集成直方图。记得增加右边距,为右轴的轴名预留一些空间。下面我们设置右边距和左边距一样。

    new.mai <- old.mai <- par("mai")
    new.mai[4] <- old.mai[2]
    par(mai = new.mai)
    
    graphics:::plot.histogram(h, freq = FALSE, col="bisque", main="Integrated Histogram",
                              xlab = paste0("Cr","(mg/dL)"), ylab="Frequeny",
                              border="black", yaxt='n')
    Axis(side = 2, at = pos, labels = freq)
    Axis(side = 4, at = pos, labels = pos)
    mtext("Density", side = 4, line = 3)
    lines(density(g), col="dimgray")
    
    par(mai = old.mai)
    

    注意我如何使用graphics:::plot.histogram 绘制hist 对象,并使用mtext 在边距上添加文本。阅读?plot.histogram?mtext 了解更多信息。

    【讨论】:

    • 感谢李哲元!这非常有效,我不必停止使用 hist()。
    • 李哲元,是的,这很酷!我希望我能支持你的答案!
    猜你喜欢
    • 2015-02-21
    • 2015-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2021-03-14
    相关资源
    最近更新 更多