【3.2】ggplot2--改变坐标轴的顺序

ggplot2作图的时候,横坐标的顺序默认是alphabetically。因为我们有分组的需要,这样得排序方式还是不怎么方便额。

一、方法一

# sample data.
d <- data.frame(Team1=c("Cowboys", "Giants", "Eagles", "Redskins"), Win=c(20, 13, 9, 12))
 
# basic layer and options
p <- ggplot(d, aes(y=Win)) + opts(axis.text.x=theme_text(angle=90, hjust=1))
 
# default plot (left panel)
# the variables are alphabetically reordered.
p + geom_bar(aes(x=Team1), stat="identity") + opts(title="Default")
 
# re-order the levels in the order of appearance in the data.frame
d$Team2 <- factor(d$Team1, as.character(d$Team1))
# same as
# d$Team2 <- factor(d$Team1, c("Cowboys", "Giants", "Eagles", "Redskins"))
 
# plot on the re-ordered variables (Team2) (middle panel)
p + geom_bar(aes(x=Team2), data=d, stat="identity") + opts(title="Order by manual")
 
# re-order by variable Win
# the variables are re-orderd in the order of the win
d$Team3 <- reorder(d$Team1, d$Win)
 
# plot on the re-ordered variables (Team3) (right panel)
p + geom_bar(aes(x=Team3), data=d, stat="identity") + opts(title="Order by var



ups.melt$exp=factor(ups.melt$exp, levels=c("UPS2only","UPS2yeast","UPS2mouse"))

人为的定义这个顺序

二、方法二

参考资料:

https://kohske.wordpress.com/2010/12/29/faq-how-to-order-the-factor-variables-in-ggplot2/

http://blog.sina.com.cn/s/blog_4a0824490102wc4b.html

药企,独角兽,苏州。团队长期招人,感兴趣的都可以发邮件聊聊:tiehan@sina.cn
个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn