【问题标题】:Plotting horizontal bars with ggplot2 and facets用 ggplot2 和构面绘制水平条
【发布时间】:2019-07-21 00:32:55
【问题描述】:

我想重现这个情节,但是ggplot2 完成的速度很慢,而且情节最后返回空白。

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))

【问题讨论】:

  • 欢迎来到 SO。我们无权访问您的数据集。请提供一个最小的可重现示例。请参阅此post 学习。重要的是,您是否尝试过查看本网站上发布的类似问题?我敢肯定有一个类似于你在这里某个地方问过的问题。这里的重点是,发布代码片段是不够的。必须展示解决问题的努力。
  • 你是对的!我编辑了我的帖子。

标签: r ggplot2 rstudio visualization data-science


【解决方案1】:

试试这个,

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 轴上绘制分类变量,y 轴必须是连续变量。

编辑 1

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

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)

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 2023-03-07
      • 2022-01-21
      • 2019-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多