2

I'm working on making a waterfall chart to show the changes across multiple years using the same categories (i.e. buckets of change). I run into issues with my categories having the same name (growth, decline, new, lost) as the output will aggregate them together. I want to see each category within a given year but without having to give them unique names (see screenshot below).

When I don't have the unique names then my code outputs a graph where each category is aggregated (one block as opposed to a block for each year). I need to somehow communicate to R that these categories are distinct (despite having same name) and need to be evaluated separately. Any help would be greatly appreciated.

Desired output Desired output is a waterfall chart


  y = c(500, 50, -10, -5, 10,
      0, 20, -15, -1, 24,
      0)
x = c(
  "2019 Revenue",
  "Growth",
  "Decline",
  "Lost",
  "New",
  "2020 Revenue",
  "Growthz",
  "Declinez",
  "Lostz",
  "Newz",
  "2021 Revenue"
)


measure = c(
  "relative",
  "relative",
  "relative",
  "relative",
  "relative",
  "total",
  "relative",
  "relative",
  "relative",
  "relative",
  "total"
)

data = data.frame(x=factor(x,levels = x) , y, measure)



fig <-
  plot_ly(
    data,
    x = ~ x,
    y = ~ y,
    measure = ~ measure,
    type = "waterfall",
    base = 0,
    decreasing = list(marker = list(
      color = "Maroon", line = list(color = "red", width = 2)
    )),
    increasing = (marker = list(color = "Teal")),
    totals = list(marker = list(
      color = "00bfff", line = list(color = 'blue', width = 3)
    ))
  )
fig1 <- fig %>%
  layout(
    title = "Profit and loss statement",
    xaxis = list(
      title = "",
      tickfont = "16",
      ticks = "outside"
    ),
    yaxis = list(title = ""),
    waterfallgap = "0.3",
    
    shapes = list(
      list(
        type = "rect",
        fillcolor = "00bfff",
        line = list(color = 'blue', width = 3),
        opacity = 1,
        x0 = -0.4,
        x1 = 0.4,
        xref = "x",
        y0 = 0.0,
        y1 = 500,
        yref = "y"
      )
    )
  )
Jan
  • 4,974
  • 3
  • 26
  • 43

1 Answers1

1

It's not the most elegant way so would be grateful if there's a function or attribute that does this automatically. I used the tickval and ticktext attributes to remove the "z" from the labels.

    fig1 <- fig %>%
  layout(
    title = "Profit and loss statement",
    xaxis = list(
      title = "",
      tickfont = "16",
      ticks = "outside",
      tickvals = c(x),
      ticktext = stringr::str_replace(x,"z","")
    ),
    yaxis = list(title = ""),
    waterfallgap = "0.3",
    
    shapes = list(
      list(
        type = "rect",
        fillcolor = "00bfff",
        line = list(color = 'blue', width = 3),
        opacity = 1,
        x0 = -0.4,
        x1 = 0.4,
        xref = "x",
        y0 = 0.0,
        y1 = 500,
        yref = "y"
      )
    )
    
    
  )



fig1 ```