如何在 R 中使用 ggplot2 创建阶梯直方图?

要使用 ggplot2 创建步进直方图,我们可以在 stat_bin 函数中使用 geom="step" 参数。例如,如果我们有一个包含单列的数据框,则可以使用以下命令创建步长直方图 - ggplot(df, aes(x))+stat_bin(geom="step",bins=30)

示例

考虑以下数据框 -

set.seed(14)
x<−rnorm(20)
df<−data.frame(x)
df
输出结果
x
1 −0.66184983
2 1.71895416
3 2.12166699
4 1.49715368
5 −0.03614058
6 1.23194518
7 −0.06488077
8 1.06899373
9 −0.37696531
10 1.04318309
11 −0.38282188
12 0.29942160
13 0.67423976
14 −0.29281632
15 0.48805336
16 0.88280182
17 1.86274898
18 1.61172529
19 0.13547954
20 1.08808601

加载 ggplot2 包并创建步骤直方图 -

示例

library(ggplot2)
ggplot(df,aes(x))+stat_bin(geom="step",bins=30)
输出结果