带有序条形图和使用构面的图形

时间:2018-05-16 16:51:14

标签: r ggplot2 tidytext

我正在尝试根据频率制作带有序条形图的图形,并使用facet使用变量两个单独的两个变量。 必须按照' n'中给出的值来排序字词。变量。因此,我的图表应该看起来像this one,它出现在整洁文本中:enter image description here

我的图表如下,单词不按值排序,我的错误是什么?: enter image description here 我的数据看起来像示例中的那个:

> d
# A tibble: 20 x 3
   word    u_c            n
   <chr>   <chr>      <dbl>
 1 apples  candidate 0.567 
 2 apples  user      0.274 
 3 melon   user      0.191 
 4 curcuma candidate 0.105 
 5 banana  user      0.0914
 6 kiwi    candidate 0.0565
 ...

按照书中提供的代码并根据我的数据进行修改,代码如下所示:

d %>% 
  mutate(word = reorder(word, n)) %>%
  ggplot(aes(word, n, fill = u_c)) + 
  geom_col(show.legend = F) +
  facet_wrap(~u_c, scales = "free_y") +
  coord_flip()

以下是dput的{​​{1}}:

d

2 个答案:

答案 0 :(得分:1)

除了GordonShumway的相关评论(因为解决方案提供了一点黑色魔法) - 你可以创建一个临时值来重新排序你的方面 - 请注意我使用forcats::fct_reorder而不是{{ 1}}

reorder

答案 1 :(得分:1)

鉴于@GordonShumway提供的信息并遵循@CPak给出的答案,下面我提供了解决此问题的完整且“棘手”且不优雅的方法。几乎整个答案(由@CPak)和另外一行最终解决了问题:

d %>%
  mutate(temp = paste(word, u_c, sep = "_")) %>%
  ggplot(aes(x = fct_reorder(temp, n), y = n, fill = u_c)) +
  geom_col(show.legend = F) +
  scale_x_discrete(labels = function(x) str_replace(x,"_candidate|_user", "")) +
  facet_wrap(~u_c, scales = "free_y") + 
  coord_flip()

enter image description here

感谢您的回答!