根据其值对变量进行分组并获得直方图
Group the variable according to its value and get a histogram
我正在尝试根据变量的值对变量进行分组并获得直方图。
例如,这是我的数据:
r <-c(1,899,1,2525,763,3,2,2,1863,695,9,4,2876,1173,1156,5098,3,3876,1,1,
3023,76336,13,003,9898,1,10,843,10546,617,1375,1,1,5679,1,21,1,13,6,28,1,14088,682)
我想按值对 r 进行分组,例如:1-5、5-10、10-100、100-500 和超过 500。然后我想得到 x 轴所在的直方图间隔类型(1-5,5-10,10-100,100-500 和大于 500)。如何解决?
如果要使用ggplot2包,代码如下:
ggplot(data=r, aes(x=r))+geom_histogram(breaks = c(1, 5, 10, 100, 500,2000,Inf))
它不起作用,R 说 "missing value where TRUE/FALSE needed"。以及如何使 bins 的 larges 相同?
在基地 R
r <-c(1,899,1,2525,763,3,2,2,1863,695,9,4,2876,1173,1156,5098,3,3876,1,1,5,
3023,76336,13,003,9898,1,10,843,10546,617,1375,1,1,5679,1,21,1,13,6,28,1,14088,682)
cut.vals <- cut(r, breaks = c(1, 5, 10, 100, 500, Inf), right = FALSE)
xy <- data.frame(r, cut = cut.vals)
barplot(table(xy$cut))
请注意,我添加了 xy
变量以方便比较值的分组方式。你可以直接把cut.vals
放到barplot(table())
.
要使用ggplot2
,可以预先计算所有的bins并绘制
ggplot(xy, aes(x = cut)) +
theme_bw() +
geom_bar() +
scale_x_discrete(drop = FALSE)
geom_histogram
最常用的控制 bin 大小的参数是 binwidth
,它对所有 bin 都是常量。
我正在尝试根据变量的值对变量进行分组并获得直方图。
例如,这是我的数据:
r <-c(1,899,1,2525,763,3,2,2,1863,695,9,4,2876,1173,1156,5098,3,3876,1,1,
3023,76336,13,003,9898,1,10,843,10546,617,1375,1,1,5679,1,21,1,13,6,28,1,14088,682)
我想按值对 r 进行分组,例如:1-5、5-10、10-100、100-500 和超过 500。然后我想得到 x 轴所在的直方图间隔类型(1-5,5-10,10-100,100-500 和大于 500)。如何解决?
如果要使用ggplot2包,代码如下:
ggplot(data=r, aes(x=r))+geom_histogram(breaks = c(1, 5, 10, 100, 500,2000,Inf))
它不起作用,R 说 "missing value where TRUE/FALSE needed"。以及如何使 bins 的 larges 相同?
在基地 R
r <-c(1,899,1,2525,763,3,2,2,1863,695,9,4,2876,1173,1156,5098,3,3876,1,1,5,
3023,76336,13,003,9898,1,10,843,10546,617,1375,1,1,5679,1,21,1,13,6,28,1,14088,682)
cut.vals <- cut(r, breaks = c(1, 5, 10, 100, 500, Inf), right = FALSE)
xy <- data.frame(r, cut = cut.vals)
barplot(table(xy$cut))
请注意,我添加了 xy
变量以方便比较值的分组方式。你可以直接把cut.vals
放到barplot(table())
.
要使用ggplot2
,可以预先计算所有的bins并绘制
ggplot(xy, aes(x = cut)) +
theme_bw() +
geom_bar() +
scale_x_discrete(drop = FALSE)
geom_histogram
最常用的控制 bin 大小的参数是 binwidth
,它对所有 bin 都是常量。