ggplot2
包有3个函数非常适合这些任务:
cut_number()
:使用(大约)相等数量的观测值创建n个组
cut_interval()
:使n个组具有相等的范围
cut_width()
:使宽度为width的组
我首选cut_number()
,因为它使用均匀间隔的分位数对观测值进行分组。以下是一个偏斜数据的示例。
library(tidyverse)
skewed_tbl <- tibble(
counts = c(1:100, 1:50, 1:20, rep(1:10, 3),
rep(1:5, 5), rep(1:2, 10), rep(1, 20))
) %>%
mutate(
counts_cut_number = cut_number(counts, n = 4),
counts_cut_interval = cut_interval(counts, n = 4),
counts_cut_width = cut_width(counts, width = 25)
)
skewed_tbl
summary(skewed_tbl$counts)
skewed_tbl %>%
ggplot(aes(counts)) +
geom_histogram(bins = 30)
![](https://i.imgur.com/ZFfcQHo.png)
skewed_tbl %>%
ggplot(aes(counts_cut_number)) +
geom_bar()
![](https://i.imgur.com/SZkEQKr.png)
skewed_tbl %>%
ggplot(aes(counts_cut_interval)) +
geom_bar()
![](https://i.imgur.com/4undogh.png)
skewed_tbl %>%
ggplot(aes(counts_cut_width)) +
geom_bar()
![](https://i.imgur.com/cVf8Ciq.png)
这段文字是由reprex package(v0.2.1)在2018年11月01日创建的。
dplyr
),我会说mutate( df , a = cut( a , breaks = quantile( a , probs = seq( 0 , 1 , 0.2 ) ) ) )
... - Simon O'Hanlon