rggplot2formattingbar-chartcurrency-formatting

Waterfall plot - how to format labels ($xx.xx)


Trying to make a waterfall chart using the Waterfalls package (seemed like the easiest solution). I'm quite new to R and ggplot (and have been browsing stackoverflow for help).

I'd like to format the labels as $xx.xx.

Here's the data:

Factors Cost
Start 119.19
Differential A -25.4
Move -0.832
EQ -5.70
Differential (Premium) 4.93
Transportation -7.37

I can get a plot with this:

waterfall(wf, calc_total=TRUE, rect_width=.4, fill_by_sign=TRUE, total_rect_color="grey", rect_border=NA) + labs(y="Cost", title ="Waterfall", x=NULL)

Basic plot

  1. If I try to add a dollar sign to the labels, it doesn't recognize "Cost".
waterfall(wf, calc_total=TRUE, rect_width=.4, fill_by_sign=TRUE, total_rect_color="grey", rect_border=NA, rect_text_labels=dollar(Cost)) + labs(y="Cost", title ="Waterfall", x=NULL)

Error: object 'Cost' not found

  1. Trying to round the labels to 2 decimal places gives me the same issue with referring to "Cost".
waterfall(wf, calc_total=TRUE, rect_width=.4, fill_by_sign=TRUE, total_rect_color="grey", rect_border=NA) + labs(y="Cost", title ="Waterfall", x=NULL) + geom_text(aes(label = round(Cost, digits = 4)))
Error in `geom_text()`:
! Problem while computing aesthetics.
ℹ Error occurred in the 23rd layer.
Caused by error:
! object 'Cost' not found

This seems like it should be pretty straightforward but I think it may be an issue with a general lack of knowledge of R.


Solution

  • The ?waterfall help page shows that it takes a parameter,

    rect_text_labels

    a character vector of the same length as values that are placed on the rectangles.

    So try adding rect_text_labels = scales::dollar_format()(wf$Cost) as an argument to the waterfall call.