更改堆积条形图中的顺序

时间:2018-11-22 08:07:36

标签: r ggplot2 bar-chart stacked-chart

尽管阅读了所有可以找到的示例,但我仍在努力固定堆积的条形图的顺序。绝对不是根据我的数据帧中的顺序进行堆叠,这似乎是一个常见的答案。

我设法将标签更改为正确的顺序,但是情节本身很固执。

我想手动输入订单,因为它没有遵循模式。

enter image description here

数据

ctrl + \

情节

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)

1 个答案:

答案 0 :(得分:0)

我不知道我是否理解您的问题。 但是您可以使用因子的水平对类型进行排序。

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()

这是结果: enter image description here