R's graph generation system ggplot2
is surprisingly versatile, but I haven't found a way to generate a waterfall chart similar to this:
How can I, using ggplot2
, generate this kind of chart?
Sample data (similar to the graph shown:
df <- data.frame(
montos = c(420, 210, -170, -140),
row.names = c('Ingresos', 'Otros ingresos', 'Costos fijos', 'Costos variables')
)
df
## montos
## Ingresos 420
## Otros ingresos 210
## Costos fijos -170
## Costos variables -140
Some previous steps are needed to be able to generate that graph, so let's try to generate it while explaining each step.
1. Initialize the data
As you put it in the question, the initialization would be something like this (I have only changed
row.names
tonombres
to put both in Spanish) and I have added the initial and final balance:We check that everything is as we wish:
2. Preserve order
To preserve the order of the data we must convert them
nombres
to the data typefactor
.3. Add columns
We add a column
id
and atipo
Then we add two columns,
start
andend
, this to put the starting and ending value of the amount in each step:If I'm not mistaken, you
df
should look like this:4. Generate the graph
Now yes, to generate the graph we do the following:
5. Result
Basically that would be it. Some improvements can be made depending on what interests you in the resulting graph.
You can see the full code in this demo .
6. Goodies
This replaces spaces with line breaks to make headings more readable.
As an alternative you can use the waterfall package implemented with lattice ( author's site ).
Example:
Result In: R-Fiddle