0
votes

My goal is to create a stacked barplot in R from a matrix, where each column in the matrix is a bar with a different color, and each bar represents the sum of all rows in the column.

Here's dummy data and bar plot scripts I'm using to trouble shoot:

m = matrix(1:9, ncol = 3, byrow = TRUE)
v = matrix(c("red", "blue", "green"), ncol=3, nrow=3, byrow=TRUE)
m #matrix of values
v #matrix of colors for each point

If I only plot row 1, colors are assigned correctly

barplot(m[1,], col=v[1,])

If I plot rows 1-3 w/o designating colors, data is stacked correctly:

barplot(m[c(1:3),])

If I plot rows 1-3 with BESIDE=TRUE, color codes correctly (but obviously is not stacked)

barplot(m[c(1:3),], col=v[c(1:3),], beside = TRUE)

If I attempt to plot rows 1-3, data stacks correctly, but color coding is not applied as needed:

barplot(m[c(1:3),], col=v[c(1:3),])

Any suggestions?

1
Ultimately I want to color code bars in groups, such as the bars 1-5 are blue, bars 6-10 are green, etc., thus the term "groups" in my post title. I'm trying to produce a plot similar to the one in the following post, but with each bar being stacked, representing three data points (aka 3 rows of a column): user-images.githubusercontent.com/17264765/… - l. spencer

1 Answers

0
votes

Try this

v <- c("red","blue","green")
barplot(m, col=v, beside=FALSE)

Each row of your data matrix will take on a single color