【问题标题】:Plotting Bigrams in Bar Chart with ggplot2使用 ggplot2 在条形图中绘制 Bigrams
【发布时间】:2018-04-20 11:04:08
【问题描述】:

我的数据如下所示:

> 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 轴上使用标签水平运行条形图。

非常感谢任何帮助!

谢谢

【问题讨论】:

  • 前 15 名是什么?只是前 15 名还是每行前 15 名?
  • 前 15 个最频繁发生 - 抱歉,我没有具体说明。立即编辑。
  • 这个? ggplot(bigrams_joined, aes(bigrams)) + stat_count(geom="bar")
  • 感谢您的建议 - 不幸的是,它试图绘制每一个值,而不是前 10 或 15 个。我有大约 35000 行,我只对前 10 或 15 个感兴趣

标签: r ggplot2 text-mining tidytext


【解决方案1】:

看起来你需要 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 年 4 月 22 日创建。

【讨论】:

  • 再次感谢 Julia,又一个完美的答案!
【解决方案2】:

你可以像这样,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()

【讨论】:

  • 感谢您的建议,不幸的是,它返回按字母顺序从 Z 到 A 排序的前 15 个。我不确定为什么这是 top_n() 的约定,但这就是它正在做的事情在这种情况下。
  • 那不是top_n函数,而是ggplot接管了。
  • 啊,我明白了——不过,谢谢你的帮助
猜你喜欢
  • 2017-09-27
  • 2023-03-22
  • 2013-04-08
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多