按降序排列堆叠的条形

我已经成功地在 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 的教程,我对此有基本的了解。提前致谢!

回答

我喜欢在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]
  


以上是按降序排列堆叠的条形的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>