How to order bars in faceted ggplot2 bar chart

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-27 22:26:59

here is a hack:

two_groups <- transform(two_groups, category2 = factor(paste(group, category)))
two_groups <- transform(two_groups, category2 = reorder(category2, rank(height)))

ggplot(two_groups, aes(category2, height)) +
  geom_bar(stat = "identity") +
  facet_grid(. ~ group, scales = "free_x") +
  scale_x_discrete(labels=two_groups$category, breaks=two_groups$category2)
  1. make UNIQUE factor variable for all entries (category2)
  2. reorder the variable based on the height
  3. plot on the variable: aes(x=category2)
  4. re-label the axis using original value (category) for the variable (category2) in scale_x_discrete.

Here is a hack to achieve what you want. I was unable to figure out how to get the category values below the tick marks. So if someone can help fix that, it would be wonderful. Let me know if this works

# add a height rank variable to the data frame
two_groups = ddply(two_groups, .(group), transform, hrank = rank(height));

# plot the graph

p_two_groups <- ggplot(two_groups, aes(-hrank, height)) +
  geom_bar(stat = "identity") +
  facet_grid(. ~ group, scales = "free_x") +
  opts(axis.text.x = theme_blank()) +
  geom_text(aes(y = 0, label = category, vjust = 1.5))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!