Last July, Alastair asked a well-framed question about ordering the legends in ggplot2.
Controlling ggplot2 legend display order
I have a related but distinct question about adjusting the order of a legend comprised of lines created with stat_summary. In other words, I am not currently on comparing values drawn from a single variable or two variables as was the case in previous examples. Rather, I am graphing calculated means.
At present the legend generated is in alphabetical order: Any Source, Classmate, Major, and so on. I would like to reorder the legend so that the items are ordered based on decreasing the intercept values in the hopes of making the graph easier to read. The preferred order would be: Any Source, Classmate, Professor, Stu. Worker @ Support Center, Teaching Assistant, Staff, Major, Other Faculty Member.
pmf0 <- ggplot(All2011QsGPASource.long, aes(x=ClassYear))
pmf1 <- pmf0 + stat_summary(aes(y=FamSuppAny,colour="Any Source"),fun.y=mean,geom="line", lwd=2)
pmf2 <- pmf1 + stat_summary(aes(y=FamClassmAny,colour="Classmate"),fun.y=mean,geom="line", lwd=2)
pmf3 <- pmf2 + stat_summary(aes(y=FamProfAny,colour="Professor"),fun.y=mean,geom="line", lwd=2)
pmf4 <- pmf3 + stat_summary(aes(y=FamStuWkrAny,colour="Stu. Worker @ Support Center"),fun.y=mean,geom="line", lwd=2)
pmf5 <- pmf4 + stat_summary(aes(y=FamTAAny,colour="Teaching Assistant"),fun.y=mean,geom="line", lwd=2)
pmf6 <- pmf5 + stat_summary(aes(y=FamStaffAny,colour="Staff"),fun.y=mean,geom="line", lwd=2)
pmf7 <- pmf6 + stat_summary(aes(y=FamMajorAny,colour="Major"),fun.y=mean,geom="line", lwd=2)
pmf8 <- pmf7 + stat_summary(aes(y=FamOthFacAny,colour="Other Faculty Member"),fun.y=mean,geom="line", lwd=2)
pmf9 <- pmf8 + theme(aspect.ratio=1) + ylab("Percentage") + xlab("Year Survey Taken")
pmf10 <- pmf9 + scale_x_continuous(breaks=c(1,2,3,4),labels=c("First Year","Sophomore","Junior","Senior")) + xlab("Class Year") + ylab("Percentage") + scale_y_continuous(labels=percent)
pmf11 <- pmf10 + scale_colour_discrete("Specific Source of Support") + labs(title="Sources of Support Over Time - Familiar Assignment")
print(pmf11)
I am currently using ggplot2 0.9.3.1, R version 3.0.1, in Mac OS X 10.7.5 and am grateful to @Kohske Takahashi for his impressive work on guide_legend. At present I can see an option for reversing the existing order of a legend but am hoping to reorder the legend in a different manner.
Thank you in advance for your help!
Andrea