sasquatch
sasquatch

Reputation: 1

resorting stacked barplot in r

I am trying to flip the order of a stacked barplot in R.

Here is a sample using the mtcars dataset.

#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.

Upvotes: 0

Views: 262

Answers (1)

Stephan Kolassa
Stephan Kolassa

Reputation: 8345

Simply flip the order of the rows in 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.

(EDIT: updated after a good catch by @MrFlick.)

Upvotes: 2

Related Questions