Ordering stacks by size in a ggplot2 stacked bar graph

こ雲淡風輕ζ 提交于 2019-11-28 09:58:29

The order that bars are drawn (bottom to top) in a stacked barplot in ggplot2 is based on the ordering of the factor which defines the groups. So the Sequence factor must be reordered based on the Abundance. But to get the right stacking order, the order must be reversed.

ab.tab$Sequence <- reorder(ab.tab$Sequence, ab.tab$Abundance)
ab.tab$Sequence <- factor(ab.tab$Sequence, levels=rev(levels(ab.tab$Sequence)))

Using your code now gives the plot you requested

ggplot(ab.tab, aes(x=Length, y=Abundance, fill=Sequence)) +
  geom_bar(stat='identity') +
  opts(legend.position="none")

I might recommend, however, something slightly different. Since you are suppressing the scale which maps color to sequence, and your description seems to indicate that you don't care about the specific sequence anyway (and there will be many), why not leave that part out? Just draw the outlines of the bars without any filling color.

ggplot(ab.tab, aes(x=Length, y=Abundance, group=Sequence)) +
  geom_bar(stat='identity', colour="black", fill=NA)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!