Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Stacked Bar Graph in ggplot [duplicate]

Tags:

r

ggplot2

My colleague and I are trying to order a stacked bar graph based on the y-values instead of alphabetically by the x-values.

The sample data is:

samp.data <- structure(list(fullname = c("LJ", "PR", 
"JB", "AA", "NS", 
"MJ", "FT", "DA", "DR", 
"AB", "BA", "RJ", "BA2", 
"AR", "GG", "RA", "DK", 
"DA2", "BJ2", "BK", "HN", 
"WA2", "AE2", "JJ2"), I = c(2L, 
1L, 3L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 2L, 3L, 3L, 3L, 
3L, 3L, 3L, 3L, 3L, 3L, 3L), S = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 2L, 2L, 3L, 2L, 3L, 2L, 3L, 3L, 
3L), D = c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 2L, 3L, 3L, 2L, 3L, 3L, 3L, 2L, 3L, 3L), C = c(0L, 2L, 1L, 
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 
2L, 3L, 3L, 3L, 3L)), .Names = c("fullname", "I", "S", "D", "C"
), class = "data.frame", row.names = c(NA, 24L))

I want to graph this has a stacked bar graph. I have been doing this with:

md <- melt(samp.data, id=(c("fullname")))
temp.plot<-ggplot(data=md, aes(x=fullname, y=value, fill=variable) ) + geom_bar()+ opts(axis.text.x=theme_text(angle=90))+ opts(title = "Score Distribtion")
ggsave(temp.plot,filename="test.png")

But I ultimately want to sort by the sum of the 4 variables (I, S, D, and C) instead of the alphabetical order of the fullnames.

Any help is greatly appreciated! Thank you!!

like image 675
Jeff Erickson Avatar asked Nov 18 '11 17:11

Jeff Erickson


1 Answers

The general (non ggplot-specific) answer is to use reorder() to reset the factor levels in a categorical column, based on some function of the other columns.

## Examine the default factor order
levels(samp.data$fullname)

## Reorder fullname based on the the sum of the other columns
samp.data$fullname <- reorder(samp.data$fullname, rowSums(samp.data[-1]))

## Examine the new factor order
levels(samp.data$fullname)
attributes(samp.data$fullname)

Then just replot, using code from the original question

md <- melt(samp.data, id=(c("fullname")))
temp.plot<-ggplot(data=md, aes(x=fullname, y=value, fill=variable) ) + 
               geom_bar()+ 
               theme(axis.text.x=theme_text(angle=90)) + 
               labs(title = "Score Distribtion")
## ggsave(temp.plot,filename="test.png")

enter image description here

like image 84
Josh O'Brien Avatar answered Sep 28 '22 07:09

Josh O'Brien