rem*_*emi 1 select r count ggplot2 dplyr
目的是选择/过滤数据帧中具有最高频率(发生次数)的前3个(或n个)事件,然后使用ggplot2中的小节图绘制这些事件。
这个例子:
library(dplyr)
df <- data.frame(
type=c("car","bike","horse","boat","yacht","train"),freq=c(20,2,5,60,11,10))
Run Code Online (Sandbox Code Playgroud)
到目前为止,我可以安排df:
df_order <- df %>%
arrange(desc(freq))
[1] df_order
type freq
1 boat 60
2 car 20
3 yacht 11
4 train 10
5 horse 5
6 bike 2
Run Code Online (Sandbox Code Playgroud)
理想的结果是仅选择前3个,types然后使用小节图绘制它们。我认为count会很有用,但不确定如何做到这一点。有任何想法吗?
在根据“ freq”列(arrange(...))对数据集进行排序之后,我们可以使用slice,使用ggplot,在中指定'x'和'y'变量的前3个值aes,并使用geom_bar
library(ggplot2)
library(dplyr)
df %>%
arrange(desc(freq)) %>%
slice(1:3) %>%
ggplot(., aes(x=type, y=freq))+
geom_bar(stat='identity')
Run Code Online (Sandbox Code Playgroud)
另一个选择是top_n方便的包装器,它使用filter并min_rank在'freq'列中选择顶部的'n'(3)个观测值ggplot并按上述方式使用。
top_n(df, n=3, freq) %>%
ggplot(., aes(x=type, y=freq))+
geom_bar(stat='identity')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4455 次 |
| 最近记录: |