排序barplot列ggplot

时间:2013-02-26 16:37:30

标签: r sorting bar-chart ggplot2

我有这个R代码来生成以下条形图:

d <- data.frame(case = c(1,2,3,4), 
                var=c('foo', 'foo', 'foo', 'foo','bar', 'bar', 'bar', 'bar'), 
                val=c(9,2,2,4,6,1,2,3))
d$var <- as.factor(d$var)
d$case <- as.factor(d$case)
ggplot(d, aes(x = case, y = val, fill = var)) + scale_x_discrete() + geom_bar(position="dodge")

enter image description here

如何按“bar”的值对条形图进行排序?

免责声明:这可能与https://stackoverflow.com/questions/10746342/sorting-ggplot2-box-plot-by-2-columns重复,但未得到回答,所以......

1 个答案:

答案 0 :(得分:5)

使用order获取按bar的值排序的列,并在foo中复制它。然后将此列用于x

d$case <- match(d$val[d$var == "bar"], sort(d$val[d$var == "bar"]))
d$case <- factor(d$case, levels=1:4)
# now use this:
ggplot(d, aes(x = case, y = val, fill = var)) +  
         geom_bar(position="dodge", stat="identity")

(或等效地)

 ggplot(d, aes( x= order, fill = var)) + geom_bar(aes(weights=val), position="dodge")

enter image description here