r - 按降序排列堆叠的条形图
问题描述
我已经成功地在 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]
推荐阅读
- ios - 使用表单时视图之间出现随机白线
- java - 将方法(java)中的值作为参数传递
- typescript - Typescript 编译器允许将 JSON 对象分配给类型化的类变量
- azure - 如何在运行时重命名 Databricks 作业集群名称
- java - 我可以设置 JVM 崩溃小型转储的输出位置吗?
- python - 沿特定维度洗牌张量
- python - Python中的连续图像遮罩
- spring-boot - KeyCloak Spring Boot - 在验证成功时添加自定义代码
- oracle - Oracle DBMS_Scheduler 每天上午 9:10 和 11:30 运行 DBMS_JOB
- jquery - 向每个 javascript 页面添加代码的快捷方式(使用可变 jquery 选择器)