[英]Reorder bars in geom_bar by multiple factors
I want my plot to be ordered by its highest column value, but for more than one variable: first for vs, then s, then us and within for its values. 我希望以最高列值对图进行排序,但要使用多个变量:首先是vs,然后是s,然后是我们,其内是其值。 Ie first bar shows ID 14 with 2 counts in VS then ID 10, then ID 16 (because 10 has a higher value for S than 16).
即第一栏显示ID 14,其中VS中有2个计数,然后显示ID 10,然后是ID 16(因为10的S值大于16)。 I've came across the reorder function.
我遇到过重新排序功能。 But my code does not even reorder for one value...
但是我的代码甚至没有为一个值重新排序...
# use data from library(MM) and melt
data(wilson, package = "MM")
non_met <- as.data.frame(non_met)
non_met$ID <- seq(1,nrow(non_met))
mhouse <- melt(non_met, id=c("ID"))
ggplot(mhouse, aes(x=reorder(ID, -value), y=value, fill = variable)) +
geom_bar(stat = "identity", lwd=0.5, color="white")
Next I tried to change my factor but that just inverts the colouring 接下来,我尝试更改因子,但这只会使颜色反转
mhouse$variable <- factor(mhouse$variable, levels=c("VS","S","US"))
head(mhouse[order(mhouse$variable, -mhouse$value),])
# ID variable value
#50 14 VS 2
#45 9 VS 1
#46 10 VS 1
#52 16 VS 1
#37 1 VS 0
#38 2 VS 0
(still not quite the right order) (仍然不是正确的顺序)
yes, here's one solution: 是的,这是一种解决方案:
data(wilson, package = "MM")
non_met <- as.data.frame(non_met)
non_met$ID <- seq(1,nrow(non_met))
non_met <- non_met[order(-non_met$VS, -non_met$S, -non_met$US),]
non_met$order <- seq(1,nrow(non_met))
mhouse <- melt(non_met, id=c("ID", "order"))
ggplot(mhouse, aes(x=reorder(ID, order), y=value, fill = variable)) +
geom_bar(stat = "identity", lwd=0.5, color="white")
but I'm open to any other idea about that problem 但我对这个问题有其他想法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.