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"))






个人公众号,比较懒,很少更新,可以在上面提问题,如果回复不及时,可发邮件给我: tiehan@sina.cn

Sam avatar
About Sam
专注生物信息 专注转化医学