【问题标题】:How do I plot a bar_plot with facet_wrap function in r?如何在 r 中绘制带有 facet_wrap 函数的 bar_plot?
【发布时间】:2019-10-13 04:15:15
【问题描述】:

我正在尝试为每年最常使用的单词绘制条形图,但 ggplot 仅绘制一个图表


word frequency Year
easy use                            easy use         9 2019
value money                      value money         8 2019
project management        project management         4 2019
business management      business management         3 2019
customer serviceâ€\u009d customer serviceâ€\u009d    3 2019
everything need              everything need         3 2019

tail(unified)


word frequency Year
workflows support workflows support         1 2014
working people       working people         1 2014
works helpful         works helpful         1 2014
worth try1                worth try         1 2014
write invoices       write invoices         1 2014
years research       years research         1 2014




ggplot(head(unified,25), aes(reorder(word,-frequency), frequency)) +  
  geom_bar(stat = "identity") + facet_wrap(~Year) + theme(axis.text.x = element_text(angle=90, hjust=1)) +  xlab("Bigrams") + ylab("Frequency") +
  ggtitle("Most frequent bigrams for all years")


我的 ggplot 只生成 2019 年的条形图。请帮助

【问题讨论】:

  • 您的意思是将head(unified,25) 放入ggplot 中吗? ggplot 可能只读取前 25 行。
  • 是的,我只需要前 25 个条目
  • 我想你想要像library(dplyr); dplyr::group_by(unified, Year) %>% dplyr::top_n(25, frequency) 这样的东西作为ggplotdata 参数的输入
  • 我想为前 25 个单词在所有年份中对应的频率绘制一个条形图

标签: r ggplot2 bar-chart facet-wrap


【解决方案1】:

您可以使用dplyr::group_bydplyr::top_n 选择按年份排名前25 位的最常用词。

library(tidyverse)

n <- 1000
t <- 4

unified <- data.frame(
    word = sample(letters[1:8], n * t, replace = TRUE),
    Year = sort(rep(1:t, n))
  ) %>%
  dplyr::group_by(Year) %>%
  dplyr::count(word, name = "frequency") %>%
  dplyr::arrange(Year, desc(frequency)) %>%
  dplyr::top_n(25, frequency) %>%
  dplyr::select(word, frequency, Year) %>%
  dplyr::ungroup()


ggplot(unified, aes(reorder(word, -frequency), frequency)) +
  geom_bar(stat = "identity") +
  facet_wrap(~Year, scales="free") +
  theme(axis.text.x = element_text(angle=90, hjust=1)) +
  xlab("Bigrams") +
  ylab("Frequency") +
  ggtitle("Most frequent bigrams for all years")

reprex package (v0.3.0) 于 2019 年 10 月 13 日创建

【讨论】:

    猜你喜欢
    • 2022-12-25
    • 2020-04-29
    • 2021-03-05
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 2017-02-26
    • 2021-07-05
    相关资源
    最近更新 更多