首页 > 解决方案 > 按降序排列堆叠的条形图

问题描述

我已经成功地在 R 中制作了一个堆积条形图,其中几个不同类别的百分比加起来为 100%。数据框如下所示:

 sujeito epentese vozeamento teste posicao palavra tipo  ortografia cseguinte
   <chr>   <chr>    <chr>      <chr> <chr>   <chr>   <chr> <chr>      <chr>    
 1 a       1        1          P     L       alpes   ps    ces        d_v      
 2 a       0        1          P     L       crepes  ps    ces        d_v      
 3 a       0        0          P     L       chopes  ps    ces        d_v      
 4 a       1        0          P     L       jipes   ps    ces        d_d      
 5 a       1        0          P     L       naipes  ps    ces        d_d      
 6 a       0        0          P     L       xaropes ps    ces        d_d      
 7 a       0        0          P     L       artes   ts    ces        d_v      
 8 a       0        0          P     L       botes   ts    ces        d_v      
 9 a       0        0          P     L       dentes  ts    ces        d_v      
10 a       0        0          P     L       potes   ts    ces        d_d      
# ... with 421 more rows

然后我使用 ggplot 和 deplyr 制作了一个显示这些百分比的堆叠条形图。我使用了这段代码:

dadospb%>%
  group_by(tipo, epentese)%>%
  summarise(quantidade = n())%>%
  mutate(frequencia = quantidade/sum(quantidade))%>%
  ggplot(., aes(x = tipo, y = frequencia, fill = epentese))+
  geom_col(position = position_fill(reverse=FALSE))+
  geom_text(aes(label = if_else(epentese == 1, scales::percent(frequencia, accuracy = 1), "")), vjust = 0, nudge_y = .01) +
  scale_y_continuous(labels=scales::percent)+
  labs(title = "Epenthesis rates by cluster type on L1 Portuguese")+
  theme(plot.title = element_text(hjust = 0.5))+
  xlab("Cluster Type")+ylab("Frequency")

不过,我的意图是让它成为这张图片右侧的图表,列按降序排列: 在此处输入图像描述

我尝试了不同的软件包并操作 group_by,但仍然没有运气。我希望这不是多余的。我在网上遇到的涉及操作 Tidyverse 的教程,我对此有基本的了解。提前致谢!

标签: rggplot2bar-chart

解决方案


我喜欢forcats在进入 ggplot 之前使用该包对类别进行排序。在这种情况下,我们可以fct_inorder在按照 epentese 的顺序(所以 0 首先出现)然后是 frecuencia 对数据进行排序之后使用。然后它变成一个有序因子,并以该顺序在 ggplot 中绘图。(看看我的虚构数据中集群 4 是如何出现在集群 3 之前的。)

我使用 mtcars 但重命名为您的数据名称:

library(dplyr); library(forcats)
# Prep to make mtcars look like your data
mtcars %>%
  mutate(vs = as.character(vs)) %>%
  group_by(tipo = carb, epentese = vs) %>%
  summarise(quantidade = sum(wt))%>%
  mutate(frequencia = quantidade/sum(quantidade)) %>%
  ungroup() %>%


  # Arrange in the way you want and then make tipo an ordered factor
  # I want epentese = 1 first, then descending frecuencia
  # When ggplot receives an ordered factor, it will display in order
  arrange(desc(epentese), -frequencia) %>%  
  mutate(tipo = tipo %>% as_factor %>% fct_inorder) %>%
  ...
  [Your ggplot code]
  

在此处输入图像描述


推荐阅读