简体   繁体   English

如何在R中订购堆叠式barplot?

[英]How to order a stacked barplot in R?

I couldn't find the answer to this problem, so I'm posting it. 我找不到此问题的答案,所以我将其发布。

I have a stacked barplot that I use to compare the occurrence of different values in my data 我有一个堆叠的条形图 ,用于比较数据中不同值的出现

Now, I would like to order it in a decreasing order, starting with the biggest combined value. 现在,我要从最大的组合值开始按降序排序。 I tried using the method I use for normal barplots: 我尝试使用用于普通条形图的方法:

barplot(combined[order(combined, decreasing = T)],
    horiz = T,
    las=1,
    xlim = c(0,60),
    col = c('lightblue','darkblue'))

but it produces a barplot that is no longer stacked 但它会产生一个不再堆叠的条形图

Is there a way to order it properly? 有办法正确订购吗? I've seen some solutions with ggplot, but I'd prefer sticking to standard barplots, if it's possible. 我已经看到了ggplot的一些解决方案,但如果可能的话,我宁愿坚持使用标准条形图。

Thanks! 谢谢!

Your problem is that you're using a matrix inside barplot() function. 您的问题是您在barplot()函数中使用了矩阵。 When you use order and compute combined[order(combined, decreasing=T)] the result is a vector. 当您使用订单并计算combined[order(combined, decreasing=T)] ,结果是一个向量。 If you want to order your columns with no regard to which color would have precedence you may use this code: 如果要排序列时不考虑哪种颜色优先,则可以使用以下代码:

barplot(combined[,order(apply(combined, 2, max))])

What this does is to apply the function max() on the columns (margin 2, margin 1 would be rows) of your matrix. 这样做是在矩阵的列(边距2,边距1将是行)上应用max()函数。 Then you'll have a matrix ordered by the maximum value of each column. 然后,您将得到一个矩阵,该矩阵按每列的最大值排序。

I'm using the following example to explain the method 我正在使用以下示例来说明方法

num <- c(1, 8, 4, 3, 6, 7, 5, 2, 11, 3)
cat <- c(letters[1:10])
data <- data.frame(num, cat)

Now, to generate barplot in decreasing order 现在,以降序生成条形图

barplot(data[order(data[,1],decreasing=FALSE),][,1],names.arg=data[order(data[,1],decreasing=FALSE),][,2], horiz = TRUE)

在此处输入图片说明

Hope this example helps. 希望这个例子有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM