简体   繁体   English

Ggplot2中的频率密度直方图

[英]Frequency density histogram in Ggplot2

I would like to draw up a histogram with varying bin width and no gaps between bins in ggplot.我想绘制一个具有不同 bin 宽度且 ggplot 中的 bin 之间没有间隙的直方图。 So exactly like in this question , but in GGPLOT.就像在这个问题中一样,但是在 GGPLOT 中。

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.所以我希望 X 轴从 0-5,5-15,15-20,20-30 和 30-40 开始,并适当地绘制条形图。

Thanks.谢谢。

I will start with a recommendation of ggplotify package which enable easy translation of any base plot to ggplot format.我将从推荐ggplotify包开始,它可以轻松地将任何基本图转换为 ggplot 格式。 This might be useful in many cases.这在许多情况下可能很有用。

breaks <- c(0, 5, 15, 20, 30, 40)
counts <- c(0.2, 0.1, 1.2, 0.4, 0.4)

gg <- ggplotify::as.ggplot(
~barplot(counts, diff(breaks),
  names = sprintf("[%g,%g)", breaks[-length(breaks)], breaks[-1]),
  cex.names = 0.5,
  space = 0
))

class(gg)
#> [1] "gg"     "ggplot"

gg

To my answer I will add @MrFlick solution too, as it is only a comment.对于我的回答,我也会添加 @MrFlick 解决方案,因为它只是一个评论。 It is worth to show how good it works.值得展示它的效果如何。

library(ggplot2)

ggplot(data.frame(left = c(0, 5, 15, 20, 30), 
                  right = c(5, 15, 20, 30, 40), 
                  freq = c(.2, .1, 1.2, .4, .4)) ) +
geom_rect(aes(xmin = left, xmax = right, ymin = 0, ymax = freq), 
          color = "black", 
          fill = NA)

Created on 2021-07-13 by the reprex package (v2.0.0)reprex 包( v2.0.0 ) 于 2021 年 7 月 13 日创建

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM