5

Hi in base graphics in R, I would like to overlay a bar plot on a chart which has irregularly spaced points on a curve. The bars should represent the change in these points since the previous sample. But I would like the bars to align to the points in the horizontal direction, so there should basically be a lot of whitespace, and wherever there's a point in the line chart, a bar should also appear at the same x-axis location, showing the change. The bottom of bars will start either on the x-axis (i.e. at y=0), or possibly underneath as a separate chart.

How would I go about doing this in R?

I know I can do this with bloxplots, as you can see in the chart in question below, where the boxes align to the various points (which are, fyi, south african government bonds). Now how do I add the bar plot?

enter image description here

Thomas Browne
  • 819
  • 1
  • 16
  • 28
  • oh by the way - I hesitated as to whether to put this here or on stack overflow - moderator pls advise. Didn't want to post it to both. – Thomas Browne Aug 29 '11 at 14:24

1 Answers1

10

barplot() is just a wrapper for rect(), so you could add the bars yourself. This could be a start:

x    <- sort(sample(1:100, 10, replace=FALSE)) # x-coordinates
y    <- log(x)                                 # y-coordinates
yD   <- c(0, 2*diff(y))                        # twice the change between steps
barW <- 1                                      # width of bars

plot(x, y, ylim=c(0, log(100)), pch=16)
rect(xleft=x-barW, ybottom=0, xright=x+barW, ytop=yD, col=gray(0.5))

enter image description here

Your second idea could be realized by splitting the device region with par(fig).

par(fig=c(0, 1, 0.30, 1))                    # upper device region
plot(x, y, ylim=c(0, log(100)), pch=16)
par(fig=c(0, 1, 0, 0.45), bty="n", new=TRUE) # lower device region
plot(x, y, type="n", ylim=c(0, max(yD)))     # empty plot to get correct axes
rect(xleft=x-barW, ybottom=0, xright=x+barW, ytop=yD, col=gray(0.5))

enter image description here

caracal
  • 11,549
  • 49
  • 63