rggplot2graphwaterfall

R ggplot2 waterfall problems


Hi I'm getting an error

Error: Discrete value supplied to continuous scale

when I execute below. Following a simple R waterfall tutorial at https://www.jigsawacademy.com/waterfall-charts-using-ggplot2-in-r/.

Wondering if this is outdated and I am missing something simple.

library(ggplot2)
library(dplyr)
balance <- data.frame(
  desc = c(
    "Starting Cash",
    "Sales",
    "Refunds",
    "Payouts",
    "Court Losses",
    "Court Wins",
    "Contracts",
    "End Cash"
  ),
  amount = c(2000, +3400, -1100, -100, -6600, 3800, 1400, 2800)
)
balance$desc <- factor(balance$desc, levels = balance$desc)
balance$id <- seq_along(balance$amount)
balance$type <- ifelse(balance$amount > 0, "in","out")
balance[balance$desc %in% c("Starting Cash", "End Cash"),+"type"] <-
  "net"
balance$end <- cumsum(balance$amount)
balance$end <- c(head(balance$end, -1), 0)
balance$start <- c(0, head(balance$end, -1))
balance <- balance[, c(3, 1, 4, 6, 5, 2)]

ggplot(balance, aes(desc, fill = type, x = desc)) + geom_rect(aes(
  xmin = id - 0.45,
  xmax = id + 0.45,
  ymin = end,
  ymax = start
))


Rstudio version 1.3.1073
R - version 4.0.2
ggplot2 - version 3.3.2

Any ideas?

Thanks


Solution

  • Making this slight changes on your code, I got this:

    library(ggplot2)
    library(dplyr)
    #Data
    balance <- data.frame(
      desc = c(
        "Starting Cash",
        "Sales",
        "Refunds",
        "Payouts",
        "Court Losses",
        "Court Wins",
        "Contracts",
        "End Cash"
      ),
      amount = c(2000, +3400, -1100, -100, -6600, 3800, 1400, 2800),
      stringsAsFactors = F
    )
    balance$desc <- factor(balance$desc, levels = balance$desc)
    balance$id <- seq_along(balance$amount)
    balance$type <- ifelse(balance$amount > 0, "in","out")
    balance[balance$desc %in% c("Starting Cash", "End Cash"),"type"] <- "net"
    balance$end <- cumsum(balance$amount)
    balance$end <- c(head(balance$end, -1), 0)
    balance$start <- c(0, head(balance$end, -1))
    balance <- balance[, c(3, 1, 4, 6, 5, 2)]
    #Plot
    ggplot(balance, aes(desc, fill = type)) + geom_rect(aes(
      x = desc,
      xmin = id - 0.45,
      xmax = id + 0.45,
      ymin = end,
      ymax = start
    ))
    

    Output:

    enter image description here

    I followed the directions in the web page you included in your question.