2
votes

Is there a way in base R to manually add a second barplot to an existing one. I know how to do it if the two series are from the same data object (using barplot( ... beside=T)) or I guess one could draw rectangles (rect(...)) which barplot wraps. If your data is from different objects how can you then do it with the barplot function ? How to control bar positions?

I tried this using the space parameter (obviously not working):

h1 <- c(10,5,1)
h2 <- c(8, 3, 1)
barplot(h1, width = 0.5, space = 2, col='red')
barplot(h2, width = 0.5, space = 2.5, col='blue', add=T)

It is impossible to get the bars besides each other as when using the beside=T argument.

enter image description here

Desired output is something along this:

barplot(matrix(c(h1, h2), nrow=2, byrow=T), beside=T, col=c('red', 'blue'))

enter image description here

UPDATE: how it works

In order for me to finally - I hope - understand the width and space arguments, we can plot an axis and play with the parameters for the blue data.

barplot(h1, width = 0.5, space = 2, col='red')
axis(1, seq(0, 10, 0.5)) #way out of the plot region
barplot(h2, width = 0.25, space = c(4,2,4), col='blue', add=T)

enter image description here

From this it seem as (correct me if I am wrong):

1. width is the width of each bar - recycled as necessary

2. space controls the space to the previous bar (to the left) or to 0 for the first bar, and is calculated as width*space for the current bar - recycled as necessary. So the first blue bar starts at (space to 0) 0.25*4 = 1 and its right side is at 1+0.25 = 1.25; the second bar starts at 1.25+0.25*2 = 1.75, and its right side is at 1.75+0.25 = 2. And so forth...

1

1 Answers

3
votes

You can do this:

h1 <- c(10,5,1)
h2 <- c(8, 3, 1)
barplot(h1, width = 0.5, space = 2, col='red')
barplot(h2, width = 0.5, space = c(3,2,2), col='blue', add=T)

And this will be the output:

enter image description here