使用reorder排列ggplot2绘制的barplot

标签:
杂谈 |
分类: R |
Ordering the bars of a stacked bar graph using
ggplot2 http://t.cn/8FF6X2A
ggplot(mtcars, aes(factor(mtcars$gear)))+
geom_bar()
ggplot2避免使用table过的数据,而是直接对原始数据进行操作。比如:
counts <- table(mtcars$gear)
barplot(counts, main="Car Distribution",
xlab="Number of
Gears")
barplot(counts, main="Car Distribution",
而使用ggplot2的时候变得更为直接:
有些时候bar的排列是按造变量的类型区分的。对于字符型变量,如国家名称,按照字母顺序排。这显然不是我们要的结果。而重新排列则主要是用reorder的方法。
例如,在这个例子中,两个变量都是字符型。
v1 <- sample(c("I","S","D","C"), 200, rep=T)
v2 <- sample(LETTERS[1:24], 200, rep=T)
my.df <- data.frame(v1, v2)
使用ggplot2
ggplot(my.df, aes(factor(my.df$v1)))+geom_bar()
果然需要重排。
reorder的方法也很简单:x=reorder(v2,rep(1,length(v2)),sum)。reorder这个命令把第一个变量v2当成类别变量(categorical variable), 依据第二个变量的数值来重新排列它的levels。也就是说reorder的核心是改变factor类型变量的levels。例如,我们想要打破原来的以字母顺序排列的levels。这里构造了每一行的数字都是1。然后sum起来,算所有的levels的顺序,就是我们想要的了。
ggplot(my.df, aes(x=reorder(v2,rep(1,length(v2)),sum),fill=v1)) + geom_bar() + theme(axis.text.x=element_text(angle=90)) + labs(x="fullname")
http://s2/mw690/001mb2IGgy6H7w8nFER91&690
另一个类似的例子:
http://quantitative-ecology.blogspot.com/2007/10/reorder-factor-levels.html
## generate data
x = factor(sample(letters[1:5],100, replace=TRUE))
print(levels(x)) ## This will show the levels of x are "Levels: a b c d e"
## To reorder the levels:
## note, if x is not a factor use levels(factor(x))
x = factor(x,levels(x)[c(4,5,1:3)])
print(levels(x)) ## Now "Levels: d e a b c"