代码之家  ›  专栏  ›  技术社区  ›  Vipul Sharma

plotly.js不同颜色的瀑布图

  •  1
  • Vipul Sharma  · 技术社区  · 7 年前

    我想用plotlyjs创建一个瀑布图,与以前的值相比,它显示了起伏。向上用绿色表示,向下用红色表示。

    绘图站点上给出的示例对于不同的值范围具有不同的颜色,并且与上下不相关。

    1 回复  |  直到 7 年前
        1
  •  0
  •   Ruben Helsloot Rez    7 年前

    实际上,可以将颜色数组传递给Plotly。

    如果有一个值差异数组,比如 [200, 400, -300, -150, -150]

    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>