tags:

views:

135

answers:

2

A cashflow diagram is often used when explaining derivatives in financial engineering. It shows the payoffs at different times. I couldn't find a great example online, but it looks something like this:

alt text

I would like to make something roughly equivalent using ggplot2. My thought was to use a stacked bar plot, where the zero axis is somewhere in the middle. Does anyone know how to do this?

Here's some example data:

data.frame(time=c(1, 2, 3), positive=c(5, 0, 4), negative=c(-2, 0, 0))

Edit:

Thanks to Hadley's answer; the resulting image looks like:

alt text

With boxes it looks like:

alt text

+1  A: 

I suggested this to Khanh once for RQuantLib. This could now be your first patch :)

One issue, I think, is that you may not want full axis on either side -- long-dated zeros would have too little on the x-axis, and for standard bonds the different payout between coupons and par amount would likely look odd too.

Then again, this is R and fortune("yoda") still applies.

Dirk Eddelbuettel
Neat idea. Let's see what we come up with and then think about the patch.
Shane
+2  A: 

Here's one attempt.

ggplot(df, aes(time, xend = time)) + 
  geom_segment(aes(y = 0, yend = positive, colour = "positive"),
    position = "stack", arrow = arrow()) + 
  geom_segment(aes(y = 0, yend = negative, colour = "negative"), 
    position = "stack", arrow = arrow()) + 
  scale_colour_manual("Direction", 
    values = c("negative" = "red", "positive" = "black"))

But I think you really need to stack the values yourself, because you don't get quite enough control with ggplot2.

hadley
Perfect! Thanks Hadley. I actually wanted "bars" even though I wasn't clear about that, but I just changed your solution to use `geom_rect` and it works! `ggplot(df, aes(time, xend = time)) + geom_rect(aes(xmin=time, xmax=time+1, ymin = 0, ymax = positive, fill = "positive")) + geom_rect(aes(xmin=time, xmax=time+1, ymin = 0, ymax = negative, fill = "negative")) + scale_fill_manual("Direction", values = c("negative" = "red", "positive" = "black"))`
Shane