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
331 views
in Technique[技术] by (71.8m points)

r - Ordering of bars in ggplot

I have looked through the answers in this forum but cannot seem to find an answer to this specific problem. I have the following data and want to create a bar chart where the bars are ordered from largest to smallest in terms of "Value", rather than having them in alphabetical order:

breadth_data <- read.table(textConnection("Stakeholder  Value
'Grantseekers'  0.90
'Donors'    0.89
'Community' 0.55
'Hurricane Relief Fund' 0.24
'Media' 0.19
'Employment Seekers'    0.12
'Affiliates'    0.10
'Youth' 0.09
'Women' 0.02
'Former Board Members'  0.01"), header=TRUE)

Then the basic bar chart:

c <- ggplot(breadth_data, aes(x=Stakeholder, y=Value))
c + geom_bar(stat="identity") + coord_flip() + scale_y_continuous('') + scale_x_discrete('')

I have tried many of the different reorderings and transformations I've seen on StackOverflow but I cannot seem to find one that works. I am sure this is fairly simple, but I would appreciate any help!

Thanks,

Greg

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You want function reorder():

breadth_data <- transform(breadth_data, 
                          Stakeholder = reorder(Stakeholder, Value))

Which gives:

reordered barplot

If you want them the other way round, an easy way is just to use order() on Value inside the reorder() call:

breadth_data <- transform(breadth_data,
                          Stakeholder = reorder(Stakeholder, 
                                                order(Value, decreasing = TRUE)))

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

...