加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

使用reorder排列ggplot2绘制的barplot

(2014-03-07 14:02:17)
标签:

杂谈

分类: R
Ordering the bars of a stacked bar graph using ggplot2 http://t.cn/8FF6X2A

ggplot2避免使用table过的数据,而是直接对原始数据进行操作。比如:

counts <- table(mtcars$gear)
barplot(counts, main="Car Distribution", 
   xlab="Number of Gears")

而使用ggplot2的时候变得更为直接:

 ggplot(mtcars, aes(factor(mtcars$gear)))+ geom_bar()

有些时候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"

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有