[R] ggplot: geom_bar not respecting factor order when stacking
Alexander Shenkin
ashenkin at ufl.edu
Thu Feb 4 11:24:26 CET 2016
Hi all,
ggplot2 (v2.0.0) does not seem to respect factor order when stacking
bars in geom_bar().
##################
> dput(temp)
structure(list(phylo_sig = c(0.148740270638472, 0.148740270638472,
0.148740270638472, 0.148740270638472, 0.148740270638472), trait =
c("p_corrected_percent",
"p_corrected_percent", "p_corrected_percent", "p_corrected_percent",
"p_corrected_percent"), value = c(0.031015586683513, 0.0553330412480036,
0.73674222087599, 0.114517508485538, 0.0623916427069555), varlevel =
structure(c(3L,
2L, 4L, 5L, 1L), .Label = c("species", "genus", "family", "plot_code",
"Residual"), class = "factor")), .Names = c("phylo_sig", "trait",
"value", "varlevel"), row.names = c(28L, 62L, 96L, 130L, 164L
), class = "data.frame")
> str(temp)
'data.frame': 5 obs. of 4 variables:
$ phylo_sig: num 0.149 0.149 0.149 0.149 0.149
$ trait : chr "p_corrected_percent" "p_corrected_percent"
"p_corrected_percent" "p_corrected_percent" ...
$ value : num 0.031 0.0553 0.7367 0.1145 0.0624
$ varlevel : Factor w/ 5 levels "species","genus",..: 3 2 4 5 1
> ggplot(temp, aes(x=trait, y = value)) + geom_bar(stat = "identity",
aes(fill=varlevel, order = varlevel))
##################
The code above results in the correct legend order, but incorrect order
of stacking (https://i.imgur.com/lgAxTFh.png). I have to change the
order of the actual dataframe rows in order to coerce the stacking to work:
##################
> temp = temp[c(5,2,1,3,4),]
> ggplot(temp, aes(x=trait, y = value)) + geom_bar(stat = "identity",
aes(fill=varlevel, order = varlevel))
##################
This results in correct stacking (https://i.imgur.com/baww43x.png). Any
assistance in getting ggplot to pay attention to the factor ordering
when stacking bars would be much appreciated!
Thanks,
Allie
More information about the R-help
mailing list