ggplot 2中条形图的分层子分组

时间:2016-11-08 12:27:33

标签: r ggplot2 bar-chart

这是我的数据:

hiat    clasa   total
a.a I   26
a.e A   137
a.i A   122
a.î A   11
a.o A   49
a.u A   549
ă.i A   343
ă.o C   2
ă.u A   149
î.i C   162
î.u C   11
e.a D   326
e.e I   209
e.i A   230
e.î A   117
e.o C   591
e.u A   314
i.a D   1879
i.e D   5101
i.i I   101
i.î C   1
i.o D   1657
i.u C   423
o.a D   140
o.e C   138
o.i A   350
o.î A   3
o.o I   119
o.u A   27
u.a D   254
u.ă D   1
u.e D   59
u.i C   1125
u.o D   65
u.u I   21

我想按clasa进行分组,并且每个子组内都有hiat的层次结构顺序。组的顺序应该是A,D,C,I。问题是我不知道如何编写代码。如果你可以帮我提出任何建议,我将不胜感激。

我试过这样的事情:

library(ggplot2)
setwd("D:/PROIECTUL_DOCTORAL/CAPITOLUL_DE_FONOSTATISTICA/Rstat")
Data<- read.table ("hiat2.txt", sep="\t",header=TRUE)
Data <- data.frame (mygroup = c('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'D', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'C', 'I', 'I', 'I', 'I', 'I'), 
        mysubgroup = factor (c("a.u", "o.i", "ă.i", "e.u", "e.i", "ă.u", "a.e", "a.i", "e.î", "a.o", "o.u", "a.î", "o.î", "i.e", "i.a", "i.o", "e.a", "u.a", "o.a", "u.o", "u.e", "u.ă", "u.i", "e.o", "i.u", "î.i", "o.e", "î.u", "ă.o", "i.î", "e.e", "o.o", "i.i", "a.a", "u.u")), 
        total = c(549, 350, 343, 314, 230, 149, 137, 122, 117, 49, 27, 11, 3, 5101, 1879, 1657, 326, 254, 140, 65, 59, 1, 1125, 591, 423, 162, 138, 11, 2, 1, 209, 119, 101, 26, 21))
ggplot(Data, aes(x = reorder(mygroup, +total), y = total, fill = mysubgroup)) +
    geom_bar(position = "dodge", width = 0.5, stat = "identity") 

结果图不是我需要的。组的顺序应为A,D,C,I,并且在每个组中,条形应显示从最小到最大。

2 个答案:

答案 0 :(得分:1)

试试这个

ggplot(Data1, aes(x = mygroup, y = reorder(total, mygroup), fill = mysubgroup)) + 
  geom_bar(position = "dodge", width = 0.5, stat = "identity")

enter image description here

答案 1 :(得分:0)

levels(df$clasa)<-c("A","D","C","I")
library(dplyr)
ordered=df%>%group_by(clasa)%>%arrange(clasa,hiat)
library(ggplot2)
ggplot(ordered)+geom_bar(aes(x=clasa,y=total,fill=hiat),stat = "identity",position="dodge")

给出了: enter image description here