【问题标题】:Frequency density histogram in Ggplot2Ggplot2中的频率密度直方图
【发布时间】:2021-07-13 20:19:56
【问题描述】:

我想在 ggplot 中绘制一个具有不同 bin 宽度并且在 bin 之间没有间隙的直方图。就像在这个question 中一样,但在 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

所以我希望 X 轴从 0-5,5-15,15-20,20-30 和 30-40 开始,并适当地绘制条形。

谢谢。

【问题讨论】:

  • 可能有帮助:*.com/questions/20688376/…。你的数据已经这样总结了吗?您的原始输入数据到底是什么样的。你有休息的向量吗?
  • 似乎与geom_rect: data.frame(left = c(0,5,15,20,30),right=c(5,15,20,30,40),freq=c(.2, .1, 1.2, .4, .4)) %&gt;% ggplot() + geom_rect(aes(xmin=left, xmax=right, ymin=0, ymax=freq), color="black", fill=NA) 一起非常严格

标签: r ggplot2


【解决方案1】:

我将从推荐ggplotify 包开始,它可以轻松地将任何基础图转换为 ggplot 格式。这在许多情况下可能很有用。

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

对于我的回答,我也会添加@MrFlick 解决方案,因为它只是一个评论。值得展示它的效果。

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)

reprex package (v2.0.0) 于 2021-07-13 创建

【讨论】:

    最近更新 更多