Skip to content

Solving: Ordered labels in ggplot2

After many tries, I found this link saying how to solve this annoying issue.

I will use my sample data I need to plot as A, PTR and MX.

After you plot you need to fix the order using Factor() and Levels().

me.df$Qtype = factor( me.df$Qtype, levels=c(qname))

Now just plot again.
last_plot() %+% me.df

The following lines are the full source used to solve this issue
library(ggplot2)
mysample = read.csv('sample.csv', sep="\t")
time = c("hour1", "hour2")
qname = c("A","PTR", "MX")
me = structure( c(mysample$A, mysample$PTR, mysample$MX) ,.Dim=c(2,3) ,.Dimnames=list( c(time), c(qname) ))
me.df = melt(me)
me.df = rename(me.df, c(X1="Hour", X2="Qtype"))
a = ggplot(me.df, aes(x = Hour, y = value, fill = Qtype))
a + geom_bar(stat = "identity",  position = "stack")
me.df$Qtype = factor( me.df$Qtype, levels=c(qname))
last_plot() %+% me.df

This is my ordered plot:

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload the CAPTCHA.