使用 ggplot2 和 facets 绘制单杠

Plotting horizontal bars with ggplot2 and facets

我想重现这个情节,但是ggplot2完成起来很慢,情节return最后是空的。

plot

我的代码:

library(ggplot2)

g <- ggplot(data = bigram_tf_idf2, aes(x = tf_idf, y = bigram)) + 
  geom_bar(stat = 'identity') +
  coord_flip()

g + facet_wrap(~ book, ncol = 2)

样本数据集:

bigram_tf_idf2 <- data.frame(book = c('Persuasion','Mansfield Park','Mansfield Park','Persuasion','Persuasion','Emma','Northanger Abbey','Sense & Sensibility','Emma','Pride & Prejudice'),
                            bigram = c('captain wentworth','sir thomas','miss crawford','lady russell','sir walter', 'miss woodhouse', 'miss tilney', 'colonel brandon', 'frank churchill', 'lady catherine'),
                            tf_idf = c(0.0535, 0.0515, 0.0386, 0.0371, 0.0356, 0.0305, 0.0286, 0.0269, 0.0248, 0.0247))

试试这个,

library(ggplot2)
p <- ggplot(data = bigram_tf_idf2, aes(x = bigram, y = tf_idf)) + 
  geom_bar(stat = 'identity') +
  coord_flip()

p + facet_wrap(~ book, ncol = 2)

本质上,您代码中的错误是您混淆了 x 和 y 轴变量。请记住,在 x-axis 上绘制分类变量,而 y-axis 必须是连续变量。

编辑 1

为了美化剧情,加theme()赞,

ggplot(data = bigram_tf_idf2, aes(x = bigram, y = tf_idf)) + 
  geom_bar(stat = 'identity') +
  coord_flip()+
  theme_bw()

编辑 2

要为条形添加颜色,请使用 fill

p <- ggplot(data = bigram_tf_idf2, aes(x = bigram, y = tf_idf,
                                       fill=bigram)) + 
  geom_bar(stat = 'identity') +
  coord_flip()+
  theme_bw()
p + facet_wrap(~ book, ncol = 2)

这是最终的结果和代码。

bigram_tf_idf %>%
  group_by(book) %>% 
  top_n(12) %>%
  ungroup() %>%
  mutate(book = as.factor(book),
         bigram = reorder_within(bigram, n, book)) %>% 
  ggplot(aes(bigram, tf_idf, fill = book)) + 
  geom_col(show.legend = F) +
  facet_wrap(~ book, scales = 'free_y', ncol = 2) +
  coord_flip() +
  scale_x_reordered() +
  scale_y_continuous(expand = c(0,0)) +
  labs(y = 'if_idf de bigramas por livro',
       x = NULL,
       title = 'Analysing Bigrams',
       subtitle = 'Bigrams by Book')

Plot with final result