2

I want to create a sorted bar chart (similar to the one presented here: http://flowingdata.com/2008/08/19/3-worthwhile-alternatives-to-the-pie-chart/). When I run the code below, I get something very similar, but the bars aren't sorted. How can I sort the bars so that the one with the highest frequency is at the top of the chart?

cat = c("CatA", "CatB", "CatC", "CatB", "CatB", "CatB", "CatB", "CatB", "CatB", "CatB")
dat = data.frame(Category = cat)

qplot(factor(Category), data=dat, geom="bar") + 
  geom_bar() +
  coord_flip()
4

3 回答 3

3

尝试:

dat$Category <- factor(dat$Category, levels=names(sort(tapply(dat$Category, dat$Category, length))))

并查看我的博客文章:http ://trinkerrstuff.wordpress.com/2012/10/15/how-do-i-re-arrange-ordering-a-plot/

在此处输入图像描述

于 2013-04-20T20:51:14.053 回答
2

您也可以使用基本图形来实现它:

barplot(sort(table(dat)), horiz=TRUE)
于 2013-04-20T20:30:24.933 回答
1

Roman 是对的,您需要以正确的顺序获得您的因子水平。使用@sgibbs 逻辑,这样的事情会起作用(原谅我完全不熟悉ggplot

qplot(factor(Category,levels=names(sort(table(cat)))), data=dat, geom="bar") + 
  geom_bar() +
  coord_flip()
于 2013-04-20T20:51:07.033 回答