【问题标题】:How do you use hist to plot relative frequencies in R?你如何使用 hist 在 R 中绘制相对频率?
【发布时间】:2011-05-03 15:50:45
【问题描述】:

如何使用 hist() 绘制 R 中的相对频率?

如果我执行以下操作,我会得到一个密度图,但我想要一个相对频率图:

a <- c(0,0,0,1,1,2)
hist(a, freq=FALSE)

我想查看具有以下相对频率的直方图:

.5 表示 0 到 1,

.33 表示 1 到 2,

和 .166 用于 2 到 3。

【问题讨论】:

标签: r histogram


【解决方案1】:

你可以尝试在lattice中使用histogram()函数

a <- c(0,0,0,1,1,2)
library(lattice)
histogram(a)

默认为百分比。

【讨论】:

  • 可惜它默认使用了这么难看的颜色:)
【解决方案2】:

我在 CRAN 上的 HistogramTools 包中添加了一个新函数 PlotRelativeFrequency(),它采用直方图对象并生成相对频率直方图。现在可以从 R-Forge 获得它,并将在下一个 CRAN 版本中包含在 HistogramTools 0.3 中。

基本上,你只需要对R中的默认直方图进行两次修改。首先,你需要将每个计数除以所有计数的总和,并且你需要替换y轴标签来注意它现在正在绘制相对频率。

x<-runif(100)
h<-hist(x, plot=F)
h$counts <- h$counts / sum(h$counts)
plot(h, freq=TRUE, ylab="Relative Frequency")

或者,简单地说

install.packages("HistogramTools", repos="http://R-Forge.R-project.org")
library(HistogramTools)
PlotRelativeFrequency(hist(x, plot=F))

【讨论】:

    【解决方案3】:
    hist(a, breaks=c(0, 1, 2, 3), freq=FALSE, right=FALSE)
    

    【讨论】:

      【解决方案4】:

      不是传统的直方图...

      h<-hist(yourdata)
      plot(h$mids,100*h$counts/sum(h$counts),type="h")
      

      【讨论】:

        【解决方案5】:
        histo<-hist(yourvariable)
        barplot(histo$counts/n,col="white",space=0)->bp   # n=length(yourvariable)
        axis(1,at=c(bp),labels=histo$mids)
        title(ylab="Relative Frequency",xlab="Your Variable Name")
        

        【讨论】:

          猜你喜欢
          • 2012-10-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-06-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-08
          相关资源
          最近更新 更多