8
$\begingroup$

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

$\endgroup$
0

1 Answer 1

10
$\begingroup$

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

$\endgroup$
1
  • $\begingroup$ Awesome thanks Caracal. Off I go and do it that way. $\endgroup$ Commented Aug 29, 2011 at 15:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.