Draw frequency density histogram in R

怎甘沉沦 提交于 2019-12-12 17:25:53

问题


Using R, can anyone show me how to draw a simple histogram with no gaps between the bins of the following data :-

Class Width Freq. Dist

0 <= x < 5          0.2 
5 <= x < 15         0.1
15 <= x < 20        1.2
20 <= x < 30        0.4
30 <= x < 40        0.4

So I want the X axis to go from 0-5,5-15,15-20,20-30 and 30-40 with the bars drawn appropriately.

Thanks in advance !


回答1:


How about this one?

breaks <- c(0,5,15,20,30,40)
counts <- c(0.2, 0.1, 1.2, 0.4, 0.4)
barplot(counts,
   names=sprintf("[%g,%g)",
      breaks[-length(breaks)], breaks[-1]
   ),
   space=0
)

This will give you bars of equal widths. On the other hand, If you'd like to obtain bars of various widths, type:

barplot(counts, diff(breaks),
    names=sprintf("[%g,%g)", breaks[-length(breaks)], breaks[-1]),
    space=0
)

Moreover, this will give you an "ordinary" X axis:

barplot(counts, diff(breaks), space=0)
axis(1)

And if you'd like to get axis breaks exactly at points in breaks, type:

axis(1, at=breaks)



回答2:


I would look into the "HistogramTools" package for R.

breaks <- c(0, 5, 15, 20, 30, 40)
counts <- c(0.2, 0.1, 1.2, 0.4, 0.4)
library(HistogramTools)
plot(PreBinnedHistogram(breaks, counts), main = "")



来源:https://stackoverflow.com/questions/23184722/draw-frequency-density-histogram-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!