Order of the factors changes while displayed on x axis.
Is that a feature?
fact<-factor(sample(c(1:5),20,rep=T),ordered=T)
num<-rnorm(20)
qplot(fact,num,geom="boxplot")
in plot they appear in order 43152 but
> str(fact)
Ord.factor w/ 5 levels "1"<"2"<"3"<"4"<..: 4 2 3 1 3 5 5 4 1 3 ...
Sorry if I missed something,
Thanks,
Vitalie.
Probably a bug.
That appears to be a general way the ggplot2 works. In documentation for scales_discrete:
levels(diamonds$cut)
[1] "Fair" "Good" "Very Good" "Premium" "Ideal"
qplot(cut, data=diamonds, stat="bin")
levels in the plot are inverted and "Good" and "Very Good" swapped. Apparently for no reason.
A great deal of work!!
Thanks for the package.
Vitalie.
> Using this opportunity: could someone explain how to control the order
> of factors in general?
> Are labels and breaks the way to go and what is
> the interaction between order and levels? I see the problem coming up
> here repeatedly but I don't see the big picture.
The order of factors is controlled by the factor/ordered functions
using the levels argument. The order is the one in which levels are
specified.
ggplot does not respect that currently but there is a work around
until Hadley fixes the issue (which is likely to be before you even
read this message).
data = data.frame(x=c("c","a","b","c","c","a"), stringsAsFactors =F)
qplot(data$x,geom="histogram")
# order of first occurence in the vector: c, a, b
class(data$x)
# data is still a character string
data$x = factor(data$x, levels=c("a","b","c"))
data$x
qplot(data$x,geom="histogram")
# should plot as a, b, c = the order of the levels
# I think this is a (recent) bug in ggplot. The behaviour was correct
previously IIRC.
# work around: physically order the data in the data.frame along the
order of the factor
data$x
data$x = data$x[order(as.numeric(data$x))]
data$x
qplot(data$x,geom="histogram")
# this works with any given order
data$x = factor(data$x, levels=c("b","c","a"))
data$x = data$x[order(as.numeric(data$x))]
qplot(data$x,geom="histogram")
Hope that helps.
JiHO
---
http://jo.irisson.free.fr/
-- Christian
Yup, fixed in the development version.
> # work around: physically order the data in the data.frame along the
> order of the factor
> data$x
> data$x = data$x[order(as.numeric(data$x))]
> data$x
> qplot(data$x,geom="histogram")
> # this works with any given order
> data$x = factor(data$x, levels=c("b","c","a"))
> data$x = data$x[order(as.numeric(data$x))]
> qplot(data$x,geom="histogram")
Alternatively, you can set the limits on the x axis:
+ scale_x_discrete(limits = c("b","c","a"))
Hadley