简体   繁体   English

在r中使用堆积的条形图

[英]resorting stacked barplot in r

I am trying to flip the order of a stacked barplot in R. 我试图在R中翻转堆积的条形图的顺序。

Here is a sample using the mtcars dataset. 以下是使用mtcars数据集的示例。

#using mtcars, create a table
counts <- table(mtcars$vs, mtcars$gear)

#edit row names of table
row.names(counts)[1] <- "VS = 0"
row.names(counts)[2] <- "VS = 1"

#create barplot
barplot(counts, legend = row.names(counts))

I want to flip the order of the heights of the bars, so that VS = 1 is on the bottom or VS = 0. The x-axis should remain sorted as 3,4,5. 我想翻转条形高度的顺序,以便VS = 1位于底部或VS = 0.X轴应保持排序为3,4,5。

Simply flip the order of the rows in counts : 只需按counts翻转行的顺序:

foo <- counts[c(2,1),]
barplot(foo, legend = row.names(foo))

barplot

Of course, the bottom bars are still colored darker, so this also flips the color coding. 当然,底部条纹仍然是较暗的颜色,因此这也会改变颜色编码。 If you want to keep that, adjust the col argument to barplot . 如果要保留它,请将col参数调整为barplot

(EDIT: updated after a good catch by @MrFlick.) (编辑:经过@MrFlick好评后更新。)

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

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