I have a matrix with the following entries:
dput(MilDis[1:200,])
structure(list(hhDomMil = c(\"HED\", \"ETB\", \"HED\", \"ETB\", \"PER\",
\"BUM\", \"EXP\",
If you relevel your hhDomMil as a factor like this:
o<-c("ETB" "PMA" "PER" "KON" "TRA" "DDR" "BUM" "MAT" "HED" "EXP")
d$hh<-factor(d$hhDomMil,levels=o)
then your plot will be in the order you like:
ggplot(d,(aes(x=kclust, fill=hh))) +geom_bar(position="fill")
I see that you have an order
column in your data frame which I gather is your order. Hence you can simply do.
p0 = qplot(factor(kclust), fill = reorder(hhDomMil, order), position = 'fill',
data = df1)
Here are the elements of this code that take care of your questions
reorder
factor(kclust)
factor(kclust)
I remember from a previous question of yours that the hhDomMil
corresponded to different groups, and I suspect your ordering follows the grouping. In that case, you might want to use that information to choose a color palette that makes it simpler to follow the graph. Here is one way to do it.
mycols = c(brewer.pal(3, 'Oranges'), brewer.pal(3, 'Greens'),
brewer.pal(2, 'Blues'), brewer.pal(2, 'PuRd'))
p0 + scale_fill_manual(values = mycols)
The answer to this is easily solved by getting your data formatted correctly before passing it to ggplot()
. The key is to explicitly set the levels of the hhDomMil
factor. Assuming your data are in dat
:
dat <- transform(dat, hhDomMil = factor(hhDomMil,
levels = c("ETB", "PMA", "PER", "KON",
"TRA", "DDR", "BUM", "MAT",
"HED", "EXP")))
That fixes hhDomMil
as a factor in place inside dat
, and sets the levels to be in the order you wanted:
> head(dat$hhDomMil)
[1] HED ETB HED ETB PER BUM
Levels: ETB PMA PER KON TRA DDR BUM MAT HED EXP
Notice what is happing when R coerces hhDomMil
to a factor:
> head(factor(as.character(dat$hhDomMil)))
[1] HED ETB HED ETB PER BUM
Levels: BUM DDR ETB EXP HED KON MAT PER PMA TRA
The default is to sort the levels alphabetically, which is why the plot is coming out as you show.
The best advice I can give, is to get your data correctly formatted first and only then try to plot it - don't rely on automatic or on-the-fly conversion to get this right for you; inevitably it won't be what you want.