使用 ggplot2 在条形图中绘制双字母组
Plotting Bigrams in Bar Chart with ggplot2
我的数据是这样的:
> str(bigrams_joined)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 71319 obs. of 2 variables:
$ line : int 1 1 1 1 1 1 1 1 1 1 ...
$ bigrams: chr "in practice" "practice risk" "risk management" "management is"
我想将数据集中前 10 或 15 个最常出现的二元组绘制到 ggplot2 中的条形图中,并使条形 运行 与 y 轴上的标签水平排列。
非常感谢任何帮助!
谢谢
你可以这样,dplyr 的 top_n
函数过滤前 15 个二元组 + ggplot 来绘制它们。
library(dplyr)
library(ggplot2)
bigrams_joined %>%
top_n(15, bigrams) %>%
ggplot(aes(bigrams)) +
geom_bar() +
coord_flip()
或订购:
bigrams_joined %>%
group_by(bigrams) %>%
mutate(n = n()) %>%
ungroup() %>%
top_n(15, bigrams) %>%
mutate(bigrams = reorder(bigrams, n)) %>%
ggplot(aes(bigrams)) +
geom_bar() +
coord_flip()
看起来你需要 count()
你的双字母组(来自 dplyr),然后你需要在你的情节中对它们进行排序。为此,这些天我更喜欢使用 forcats 中的 fct_reorder()
之类的东西。
library(janeaustenr)
library(tidyverse)
library(tidytext)
data_frame(txt = prideprejudice) %>%
unnest_tokens(bigram, txt, token = "ngrams", n = 2) %>%
count(bigram, sort = TRUE) %>%
top_n(15) %>%
ggplot(aes(fct_reorder(bigram, n), n)) +
geom_col() +
coord_flip() +
labs(x = NULL)
#> Selecting by n
由 reprex package (v0.2.0) 创建于 2018-04-22。
我的数据是这样的:
> str(bigrams_joined)
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 71319 obs. of 2 variables:
$ line : int 1 1 1 1 1 1 1 1 1 1 ...
$ bigrams: chr "in practice" "practice risk" "risk management" "management is"
我想将数据集中前 10 或 15 个最常出现的二元组绘制到 ggplot2 中的条形图中,并使条形 运行 与 y 轴上的标签水平排列。
非常感谢任何帮助!
谢谢
你可以这样,dplyr 的 top_n
函数过滤前 15 个二元组 + ggplot 来绘制它们。
library(dplyr)
library(ggplot2)
bigrams_joined %>%
top_n(15, bigrams) %>%
ggplot(aes(bigrams)) +
geom_bar() +
coord_flip()
或订购:
bigrams_joined %>%
group_by(bigrams) %>%
mutate(n = n()) %>%
ungroup() %>%
top_n(15, bigrams) %>%
mutate(bigrams = reorder(bigrams, n)) %>%
ggplot(aes(bigrams)) +
geom_bar() +
coord_flip()
看起来你需要 count()
你的双字母组(来自 dplyr),然后你需要在你的情节中对它们进行排序。为此,这些天我更喜欢使用 forcats 中的 fct_reorder()
之类的东西。
library(janeaustenr)
library(tidyverse)
library(tidytext)
data_frame(txt = prideprejudice) %>%
unnest_tokens(bigram, txt, token = "ngrams", n = 2) %>%
count(bigram, sort = TRUE) %>%
top_n(15) %>%
ggplot(aes(fct_reorder(bigram, n), n)) +
geom_col() +
coord_flip() +
labs(x = NULL)
#> Selecting by n
由 reprex package (v0.2.0) 创建于 2018-04-22。