I'd like to align the bottom
barplot in the following so that the groups line up vertically between the two plots:
par(mfrow = c(2, 1)) n = 1:5 barplot(-2:2, width = n, space = .2) barplot(matrix(-10:9, nrow = 4L, ncol = 5L), beside = TRUE, width = rep(n/4, each = 5L), space = c(0, .8))
I've been staring at the definition of the
width arguments to
?barplot) for a while and I really expected the above to work (but clearly it didn't):
width-- optional vector of bar widths. Re-cycled to length the number of bars drawn. Specifying a single value will have no visible effect...
space-- the amount of space (as a fraction of the average bar width) left before each bar. May be given as a single number or one number per bar. If
heightis a matrix and
spacemay 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. If not given explicitly, it defaults to
heightis a matrix and
TRUE, and to
As I read it, this means we should be able to match the group widths in the top plot by dividing each group into 4 (hence
space, since we're dividing each bar's width by 4, the average width will as well; hence we should multiply the fraction by 4 to compensate for this (hence
space = c(0, 4*.2)).
However it appears this is being ignored. In fact, it seems all the boxes have the same width! In tinkering around, I've only been able to get the relative within-group widths to vary.
Will it be possible to accomplish what I've got in mind with
barplot? If not, can someone say how to do this in e.g.
It is possible to do this with base plot as well, but it helps to pass the matrix as a vector for the second plot. Subsequently, you need to realize the space argument is a fraction of the average bar width. I did it as follows:
par(mfrow = c(2, 1)) widthsbarplot1 <- 1:5 spacesbarplot1 <- c(0, rep(.2, 4)) barplot(-2:2, width = widthsbarplot1, space = spacesbarplot1) widthsbarplot2 <- rep(widthsbarplot1/4, each = 4) spacesbetweengroupsbarplot2 <- mean(widthsbarplot2) allspacesbarplot2 <- c(rep(0,4), rep(c(spacesbetweengroupsbarplot2, rep(0,3)), 4)) matrix2 <- matrix(-10:9, nrow = 4L, ncol = 5L) barplot(c(matrix2), width = widthsbarplot2, space = allspacesbarplot2, col = c("red", "yellow", "green", "blue"))