r - 更改堆积条形图中的顺序
问题描述
尽管阅读了我能找到的所有示例,但我仍在努力修复堆叠条形图的顺序。它绝对不是根据我的数据框中的顺序堆叠的,这似乎是一个常见的答案。
我已经设法将标签更改为正确的顺序,但情节本身很固执。
我想手动输入订单,因为它不遵循模式。
数据
sdi_table_2<-read.table(text="'Over 50' 'Under 50'
'Intellectual Disability' 154814 214279
'Other Mental Health' 1387315 1012520
Injuries 240033 116167
Musculo-Skeletal 2041162 447212
'Nervous System' 530179 272756
'Circulatory, Respiratory, Endocrine, and Neoplasms' 1281261 260737
'Other and Unknown' 404973 212136", header=TRUE, check.names=F)
sdi_data_2<-as.data.frame.matrix(sdi_table_2)
sdi_data_2$type<-rownames(sdi_data_2)
sdi_data_2<-melt(sdi_data_2,id.vars = c("type"), value.name = "Beneficiaries")
sdi_data_2$variable <- as.character(sdi_data_2$variable)
colnames(sdi_data_2)[2] <- "Age"
factor(sdi_table_2$type, levels = sdi_table_2$type, ordered = TRUE)
阴谋
ggplot() +
geom_bar(aes(y = Beneficiaries, x = Age, fill = type),
data = sdi_data_2,
stat = "identity") +
theme_bw() +
scale_y_continuous(label = comma) +
scale_fill_manual(
name = "",
values = c(
"Injuries" = "orange2",
"Circulatory, Respiratory, Endocrine, and Neoplasms" =
"sandybrown",
"Nervous System" = "peachpuff",
"Intellectual Disability" = "skyblue2",
"Musculo-Skeletal" = "royalblue3",
[enter image description here][1] "Other and Unknown" =
"lightgoldenrod1",
"Other Mental Health" = "royalblue1"
),
breaks = c(
"Other and Unknown",
"Injuries",
"Circulatory, Respiratory, Endocrine, and Neoplasms",
"Nervous System",
"Musculo-Skeletal",
"Other Mental Health",
"Intellectual Disability"
)
)
解决方案
我不知道我是否理解你的问题。但是您可以使用因子的级别来订购您的类型。
sdi_data_2$type <- factor(sdi_data_2$type, levels = c("Circulatory, Respiratory, Endocrine, and Neoplasms","Nervous System","Injuries","Other Mental Health","Other and Unknown","Musculo-Skeletal","Intellectual Disability"))
sdi_data_2$Age <- factor(sdi_data_2$Age,levels = c("Under 50","Over 50"))
然后绘制:
ggplot() + geom_bar(aes(y = Beneficiaries, x = Age, fill = type), data = sdi_data_2, stat = "identity") + theme_bw()
推荐阅读
- c# - 使用 Autofixture、Moq 和 XUnit 的类中的部分模拟方法
- sql - 子查询返回超过 1 个值。当子查询跟随...或子查询用作表达式时,这是不允许的
- bamboo - Bamboo 部署项目 - 你可以从其他项目中调用项目吗?
- apache-spark - 优化 Spark 作业 - Spark 2.1
- css - Jquery UI 无法拖动选择
- stream - 没有定义事件到达时间窗口时的事件合并
- git - 调用“git revert”后了解 Git 冲突标记
- r - 如何矢量化函数以在 data.table 分配中工作
- css - 反应原生、弹性和宽度父元素
- uima - UIMA Ruta:无法初始化编辑器