r - 根据一个变量的值在堆叠条形图中排列堆叠
问题描述
我正在尝试编写一个函数,该函数在最后输出一个堆积条形图,其中堆积条形图的条形排列顺序从一个特定变量的最大百分比到最小百分比。我还没有找到一个通用的方法来做到这一点,我的最终目标是让这个过程以一种需要最少人工投入的方式完成。
我的数据看起来像这样
Swimming_style Comfort_level_label Comfort_level_scale n Total_n Percentage
Front Crawl Excellent 3 7 10 70
Front Crawl Good 2 3 10 30
Backstroke Excellent 3 4 10 40
Backstroke Good 2 4 10 40
Backstroke Fair 1 1 10 10
Backstroke Poor 0 1 10 10
Brest stroke Excellent 3 6 10 60
Brest stroke Fair 1 4 10 40
Butterfly Good 2 7 10 70
Butterfly Fair 1 1 10 10
Butterfly Poor 0 2 10 20
到目前为止,这是我的代码:
data <- arrange(data, Comfort_level_label, (Percentage))
data$Swimming_style <- factor(data$Swimming_style, levels = unique(data$Swimming_style))
ggplot(data, aes( x = Swimming_style, y = n, fill = Comfort_level_label)) +
geom_bar(position = "fill",stat = "identity") +
scale_y_continuous(labels = scales::percent_format())+
coord_flip()
哪个输出:
但是我需要图表做的是按照优秀评级从顶部最优秀到最不优秀或底部没有优秀,我很难做到这一点。
解决方案
这可能有点模棱两可,但在确定优先级时重要的是确保您始终拥有每个因素中的一个。
library(dplyr)
SS <- dat %>%
arrange(-Comfort_level_scale, -n) %>%
group_by(Swimming_style) %>%
slice(1) %>%
ungroup() %>%
arrange(Comfort_level_scale, n) %>%
pull(Swimming_style)
library(ggplot2)
dat %>%
mutate(Swimming_style = factor(Swimming_style, levels = SS)) %>%
ggplot(aes( x = Swimming_style, y = n, fill = Comfort_level_label)) +
geom_bar(position = "fill",stat = "identity") +
scale_y_continuous(labels = scales::percent_format()) +
coord_flip()
顺便说一句:应该Brest stroke
是Breast stroke
?
library(dplyr)
dat <- read.table(header=TRUE, stringsAsFactors=FALSE, text="
Swimming_style Comfort_level_label Comfort_level_scale n Total_n Percentage
Front_Crawl Excellent 3 7 10 70
Front_Crawl Good 2 3 10 30
Backstroke Excellent 3 4 10 40
Backstroke Good 2 4 10 40
Backstroke Fair 1 1 10 10
Backstroke Poor 0 1 10 10
Brest_stroke Excellent 3 6 10 60
Brest_stroke Fair 1 4 10 40
Butterfly Good 2 7 10 70
Butterfly Fair 1 1 10 10
Butterfly Poor 0 2 10 20") %>%
mutate(Swimming_style = gsub("_", " ", Swimming_style))
推荐阅读
- javascript - 解决 JavaScript 中的代码注入
- android - 设备进入深度睡眠时的 Android 作业调度程序行为
- c# - 在 asp.net mvc 中设置用户对每个应用程序的访问权限
- python - 方法不允许 Flask
- bootstrap-4 - bootstrap 4.1 删除了 pull-md-16(列拉/推)
- python - Keras LSTM 神经网络:TypeError:LSTM() 缺少 1 个必需的位置参数:'Y'
- html - Bootstrap 4:将输入水平放置
- dart - 使用 Redux 和 API 调用时如何在 Flutter 中打开下一页
- c# - 用对象重载方法
- firebase - 我们如何配置用户属性移动应用数据并将其通过 GTM 从 Firebase 发送到 Google Analytics?