Stacked Negative/Positive Time Series Using ggplot

2019-06-07 00:06发布

问题:

I'm trying to reproduce a stacked time-series graph which shows how the composition and size of a bank's balance sheet changes over time. It should look something like this:

Where assets go above the x-axis and liabilities go below it.

So far I've been able to reproduce each half of the graph successfully using ggplot():

# plot assets stack
assets.plot <- ggplot(assetsm, aes(x=dates, y=value, fill=variable)) + 
  geom_area() 


# plot liability stack
liabiln.plot <- ggplot(liabilnm, aes(x=dates, y=value, fill=variable)) +
  geom_area() 

which gives:

But when I add them together, something goes wrong:

# plot whole bs
bs.plot <- ggplot(bsm, aes(x=dates, y=value, fill=variable)) +
  geom_area()

which gives:

Taking note of the colour scale beside it and the picture above, you can see that:

  1. Only half the variables are shown (from V19 onwards).
  2. These variables happen to coincide just with the 'liabilities' half of the data (which are all supposed to be negative numbers).
  3. The total height of the stack at each point on x is equal to the total height of the liabilities stack in the graph above, but it no longer starts at y=0 - it lands on both sides of the y-axis.

I have no idea what's missing from my code to cause this - I've fiddled around with making position = "stack" explicit, as well as trying the answer to this question (same result), and I'm now at my wit's end.

I think this might be a data problem, so I've uploaded the data here. If I can make the question clearer or give extra details, let me know.

回答1:

I can't quite explain the behavior you're seeing at the moment, but when I do top/bottom type plots like these, I tend to use separate data frames an separate layer calls:

ggplot() + 
    geom_area(data = assetsm, aes(x=dates, y=value, fill=variable)) + 
    geom_area(data = liabilnm, aes(x=dates, y=value, fill=variable))

which seems to look like what you're after: