具有自定义 bin 限制和计数的 ggplot 直方图

问题描述 投票:0回答:2

我正在尝试使用

ggplot2
创建自定义直方图,但我不知道如何绘制箱。我有 24 个 bin,具有以下 bin 限制以及每个 bin 内的数据比例。

bin_limits <- c(0, 0.01, 0.025, seq(0.05, 0.95, by = 0.05), 0.975, 0.99, 1)

props <- c(0.07700, 0.03275, 0.04300, 0.05850, 0.04775, 0.04375,
           0.03750, 0.03825, 0.03250, 0.03325, 0.04000, 0.03000, 
           0.02950, 0.02675, 0.03000, 0.02950, 0.03700, 0.03725, 
           0.04325, 0.04250, 0.05425, 0.04675, 0.03575, 0.07325)

我想要的是一个直方图,显示框的限制宽度和比例的高度。我更喜欢使用

ggplot2
来完成此操作,但我也可以使用其他方法。我现在能想到的最接近的是一个具有比例的散点图,可以使用下面的代码制作。

data.frame(limit = bin_limits[-1], prop = props) %>% 
  ggplot(aes(x = limit, y = prop)) +
  geom_point() +
  ylim(0,.1)
ggplot2 histogram probability-distribution bins
2个回答
0
投票

一种简单的方法可能是重新缩放 x 轴,使其与您想要给出的标签对齐:

library(ggplot2)

bin_limits <- c(0, 0.01, 0.025, seq(0.05, 0.95, by = 0.05), 0.975, 0.99, 1)
props <- c(0.07700, 0.03275, 0.04300, 0.05850, 0.04775, 0.04375, 0.03750, 0.03825, 0.03250, 
           0.03325, 0.04000, 0.03000, 0.02950, 0.02675, 0.03000, 0.02950, 0.03700, 0.03725, 
           0.04325, 0.04250, 0.05425, 0.04675, 0.03575, 0.07325)

data.frame(x = 1:24, prop = props) |> 
  ggplot(aes(x, props)) +
  geom_col() +
  scale_x_continuous(breaks = seq(0.5, 24.5, by = 1), labels = bin_limits)

(在此示例中标签重叠,但可以缩放以使其更清晰)


0
投票
## a vector with the center of each bin
bin_ctr <- (bin_limits[-1] + bin_limits[-length(bin_limits)])/2
## a vector with the width of each bin
bin_wdt <- (bin_limits[-1] - bin_limits[-length(bin_limits)])
## put everything in a dataframe
bin_prop <- data.frame(bin_ctr, bin_wdt, props)

library(ggplot2)

ggplot(bin_prop, aes(x=bin_ctr, y=props, width=bin_wdt)) + 
  geom_bar(stat="identity", position="identity", 
           fill = "dodgerblue4", color = "white")

创建于 2024-01-26,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.