Reputation: 607
I have a data set with percentages in four categories: the top two categories are "positive" and the bottom two categories are "negative" so I want to align the boundary between 2 and 3 so it's the zero point on all the bars. (I'm plotting pairs of bars: on set of bars for ext.obs=0 and one for ext.obs=1.) Here's a portion of the data:
structure(list(ext.obs = c(0, 0, 0, 1, 1, 1), comp = c(1, 2,
3, 1, 2, 3), `1` = c(0.00617283950617284, 0.00609756097560976,
0.0111111111111111, 0, 0, 0), `2` = c(0.154320987654321, 0.195121951219512,
0.161111111111111, 0.211180124223602, 0.392638036809816, 0.23030303030303
), `3` = c(0.709876543209877, 0.676829268292683, 0.666666666666667,
0.745341614906832, 0.521472392638037, 0.721212121212121), `4` = c(0.12962962962963,
0.121951219512195, 0.161111111111111, 0.0434782608695652, 0.0858895705521472,
0.0484848484848485)), .Names = c("ext.obs", "comp", "1", "2",
"3", "4"), row.names = c(1L, 2L, 3L, 11L, 12L, 13L), class = "data.frame")
I would like to be able to put together a matrix with these data that I can just do barplot(datamatrix)
and have it come out nice. But I can't figure out any way other than plotting the top two categories and then adding the bottom two categories using barplot(..., add=T)
.
Here's the code I wrote (I actually plot 10 pairs of bars with par(mfrow=c(1, 10)
) looping though for(i in 1:10)
):
bar.loc <- barplot(t(as.matrix(tab3[c(i, i+10), c(5,6)])),
ylim=c(-0.5, 1.0),
col=my.pal[3:4],
xaxt="n",
yaxt="n",
ylab="",
xlab=components[i]
)
barplot(t(as.matrix(tab3[c(i, i+10), c(4, 3)]*(-1))),
add=T,
col=my.pal[2:1],
yaxt="n",
xaxt="n",
ylab="",
xlab="")
You can see part of the finished product here or the image is below:
Can anyone think of a more elegant way to do this?
Upvotes: 4
Views: 186
Reputation: 49640
Try this:
barplot( t(cbind(tab3[,5:6],-tab3[,6:5],-tab3[,4:3])),
col=c('lightblue','darkblue',NA,NA,'tan','brown') )
Upvotes: 1