Reputation: 17
I have a data set I am building stacked bar graphs in ggplot2. Each observation (Life) is located on the y axis with the bar graph extending parallel with the x-axis values. However, I would like to rank these variables based a ranking that is unrelated to the x-axis values (Earth, Wind, Fire and Water), but is being merged from another data set. Main Data:
Life Earth Wind Fire Water
A 2.72 1.22 0.860220476 2.86
B 2.11 1 0.660225123 2.26
C 0.67 0.31 0.1900664 0.69
Rank Data:
Life Rank
A 3
B 1
C 2
I am looking for Life B "Bar" to be at the top of the y-axis and Life A "Bar" to be at the bottom. The default just puts them in alphabetical order. How can I order these so the Rank 1 bar is at the top and Rank 3 is at the bottom?
Here is my code:
require(reshape2)
require(ggplot2)
bars1 <- read.csv("Renown.csv",header=T,skip = 0,stringsAsFactors=FALSE)
Rank <- read.csv("Rank.csv",header=T,skip = 0,stringsAsFactors=FALSE)
bars1 <- aggregate(.~Lifestyle, data=bars1, FUN=mean)
bars1 <- melt(bars1, id.vars = "Life")
bars1 <- merge(bars1, Rank, by="Life")
bars1 <- ggplot(bars1, aes(x = Life, y = value , fill=variable)) + geom_bar(stat='identity') + coord_flip()
Thanks!
Upvotes: 1
Views: 1055
Reputation: 2226
You need to turn Life
into a factor with the ordering based on Rank
bars1$Life = factor(bars1$Life, levels = Rank[order(-Rank$Rank),]$Life)
Upvotes: 1