DaedalusBloom
DaedalusBloom

Reputation: 377

Grouped, Stacked Barplot Over Time

I'm trying to plot 2 stacked bars over time. Essentially they would be like grouped bars over time (beside=TRUE), but also be stacked. Other stackoverflow questions answer similar issues, such as stacked and grouped charts, but don't work here - though please let me kow if you've seen a good example I've missed.

My strategy has been to plot the first set of bars, create space between them and try to plot the second in those spaces with whether par(new=TRUE) or add = TRUE argument in barplot. However, the second set of bars always overlap the first. Barplot documentation suggests that the offset argument should be useful, but I can't seem to find any examples using it and my own experimentation never seems to come out as expected.

Here is an example of code I've tried so far:

data1  = cbind(c(1,1.25),c(1.2,1.5),c(.75,1.2))
data2  = cbind(c(1.3,1.5),c(1,1.25),c(1.25,.75))

barplot(data1,
        space = 3,
        col = c(2,3))
barplot(data2,
        space = 3,
        col = c(4,5),
        add = TRUE)

Any suggestions or resources would be greatly appreciated.

Upvotes: 0

Views: 409

Answers (1)

Sven Hohenstein
Sven Hohenstein

Reputation: 81753

You can adjust the space parameter of the second plot. In this case, the space before the first bar needs to be larger than for the first plot. The spaces between bars, however, need to be the same. You can use the argument space = c(4, 3, 3) for the second plot.

barplot(data1,
        space = 3,
        col = c(2, 3))
barplot(data2,
        space = c(4, 3, 3),
        col = c(4, 5),
        add = TRUE)

enter image description here

Upvotes: 2

Related Questions