Elena Elena - 24 days ago 16
R Question

hierarchical subgrouping of bar charts in ggplot 2

Here is my data:

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


I would want to grop by clasa, and within each subgroup have the hierarchical order of hiat. The order of the groups should be A, D, C, I. The problem is that I don't know how to write the code. If you can help me with any suggestions, I would appreciate it. Thank you!
I tried smth like this :

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").
The resulting graph was not what I needed. The order of the groups should be A, D, C, I, and within each group, the bars should be displayes from smallest to largest.

Answer
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")

Which gives: enter image description here

Comments