Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
827 views
in Technique[技术] by (71.8m points)

r - How to order breaks with ggplot / geom_bar

I have a data.frame with entries like:

   variable  importance order
1       foo  0.06977263     1
2       bar  0.05532474     2
3       baz  0.03589902     3
4     alpha  0.03552195     4
5      beta  0.03489081     5
       ...

When plotting the above, with the breaks = variable, I would like for the order to be preserved, rather than placed in alphabetical order.

I am rendering with:

 
ggplot (data, aes(x=variable, weight=importance, fill=variable)) + 
    geom_bar() + 
    coord_flip() + opts(legend.position='none')

However, the ordering of the variable names is alphabetical, and not the order within the data frame. I had seen a post about using "order" in aes, but appears to have no effect.

I am looking to have a breaks ordering in-line with the "order" column.

There seems to be a similar question How to change the order of discrete x scale in ggplot, but frankly, did not understand the answer in this context.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

data$variable <- factor(data$variable, levels=levels(data$variable)[order(-data$order)])

From: ggplot2 sorting a plot Part II


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...