1
votes

I want to create a waterfall chart using plotlyjs which shows ups and downs as compared to its previous value. Up should be represented by green color and down with red color.

How can I create such a graph using plotly.js?

The example given on the plotly site has different colors for different value ranges and it has no connection with ups and downs.

1

1 Answers

0
votes

You can actually pass an array of colors to Plotly.

If you have an array of value differences, like [200, 400, -300, -150, -150], then you can formulate a color array like below.

const labels = ["Apples", "Oranges", "Rent", "Water", "Profit"];
const values = [200, 400, -300, -150, -150];

const colors = values.map((v) => v > 0 ? 'rgba(55,128,191,1.0)' : 'rgba(219, 64, 82, 1.0)');

// Use the cumulative sum to calculate the baseline of each bar. Use this to create a stacked bar chart with white bars below and colored bars on top
const baseline = new Array(values.length);
values.reduce((sum, val, idx) => {
  baseline[idx] = val > 0 ? sum : sum + val;
  return sum + val;
}, 0);

const trace1 = {
  x: labels,
  y: baseline,
  marker: {
    color: 'rgba(1,1,1,0.0)'
  },
  type: 'bar'
};

const trace2 = {
  x: labels,
  y: values.map(Math.abs),
  marker: {
    color: colors
  },
  type: 'bar'
};

var layout = {
  title: 'Annual Profit 2018',
  barmode: 'stack',
  paper_bgcolor: 'rgba(245,246,249,1)',
  plot_bgcolor: 'rgba(245,246,249,1)',
  width: 600,
  height: 600,
  showlegend: false,
  annotations: []
};


Plotly.newPlot('plot', [trace1, trace2], layout);
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<div id="plot"></div>