首页 > 解决方案 > 如何在 r 中绘制带有 facet_wrap 函数的 bar_plot?

问题描述

我正在尝试为每年最常使用的单词绘制条形图,但 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 年的条形图。请帮忙

标签: rggplot2bar-chartfacet-wrap

解决方案


您可以使用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 包(v0.3.0)于 2019 年 10 月 13 日创建


推荐阅读