Search code examples
rplotlatticewaterfall

R: Add values to waterfall chart


I am using the waterfall package in R to prepare waterfall charts and like to add the values to the chart.

Example code (taken from http://lamages.blogspot.de/2012/05/waterfall-charts-in-style-of-economist.html):

library(latticeExtra)
library(waterfall)
data(rasiel) # Example data of the waterfall package
rasiel
#    label          value   subtotal
# 1  Net Sales       150    EBIT
# 2  Expenses       -170    EBIT 
# 3  Interest         18    Net Income
# 4  Gains            10    Net Income
# 5  Taxes            -2    Net Income

asTheEconomist(
               waterfallchart(value~label, data=rasiel,
                              groups=subtotal, main="P&L")
               )

Results in this plot:

Plot from example

I am looking for the correct code to get something like this:

Plot modified


Solution

  • waterfallchart simply uses the lattice package with specific settings to create this type of plot. Consequently, all of the lattice functions that modify plots will work inside of waterfallchart.

    You have to set the text parameters of the panel like so:

    asTheEconomist(
      waterfallchart(value~label, data=rasiel,
                          groups=subtotal, main="P&L",
                     panel=function(x, y, ...) {
                       panel.waterfallchart(x, y, ...);
                       ltext(x=seq(1,7,1),y=c(75,75,10,1,20,15,14),
                             labels=c("+150","-170","-20","+10","+18","-2","+6"),
                             srt=90,font=2,cex=1.5)
                     }
           )
    )
    

    enter image description here