jay.sf
jay.sf

Reputation: 73262

How to define spacing of additional bar in barplot?

I want to plot y1, y0 and their ratio dy side by side. dy should appear at a small spacing behind the main bars. The (rotated) x-axis ticks should be centered under the three bars that belong together.

I've been messing around with width and space as well as at options for a while but I haven't understood the rationale behind it yet. The best solution so far was to add a new plot for dy, but it's still far from ideal, though.

barplot(rbind(d$y0, d$y1), beside=TRUE, xaxt="n", col=c("darkgrey", "white")
        # , width=c(1, 1, .2)
        , space=c(0, 2)
        )
barplot(d$dy, add=TRUE, width=.2, space=c(19, 25), col="blue", xaxt="n")
box()
axis(1, at=seq(1:7)*4 - 1.5, labels=2000:2006, las=2)

enter image description here

How can I do that with base plot? Could anyone explain how to define the parameters?

Expected Output

The expected output should be something like this.

enter image description here

Data

d <- structure(list(y0 = c(837.4, 798.6, 817.9, 882.6, 870.3, 857.9, 
776.6), y1 = c(827.1, 790, 807.7, 871.9, 861.8, 849.5, 768.2), 
    dy = c(122.999761165512, 107.688454795893, 124.709622203203, 
    121.232721504646, 97.6674709870162, 97.9135097330686, 108.163790883338
    )), class = "data.frame", row.names = c("1", "2", "3", "4", 
"5", "6", "7"))

Upvotes: 1

Views: 41

Answers (1)

G5W
G5W

Reputation: 37661

You can add the extra (blue) bar in the original boxplot to get it to line up right. I am also adding in a bar with zero height to space the blue bar. In order to make the ticks line up, save and use the return from the call to boxplot.

BP = barplot(rbind(d$y0, d$y1, rep(0,7), d$dy), beside=TRUE, 
    xaxt="n", width=c(1,1,0.4,0.2), space=c(0, 2),
    col=c("darkgrey", "white", "white", "blue"))
box()
axis(1, at=(BP[1,] + BP[2,])/2, labels=2000:2006, las=2)

Barplot

According to the barplot documentation,

If height is a matrix and beside is TRUE, space may be specified by two numbers, where the first is the space between bars in the same group, and the second the space between the groups.

so I used what you had space=c(0,2) to allow no space between bars and 2 units between groups.

Regarding the width, I wanted to keep with your original width of 1 for the two main bars and 0.2 for the smaller blue bar. I tried making the zero-height bar be width 0.2, but it seemed too close, so I widened the space bar to 0.4.

Upvotes: 4

Related Questions