首页 > 解决方案 > 图表 js 在 y 轴上有一个跨越负/正的条形图

问题描述

chartjs 中有没有办法让条形图跨越零线?例如,假设我有一个酒吧

data:[x:1, y:100]

我如何告诉它跨越 y 轴从 -100 到 100(而不是从 0 到 100)?

我在这里有一个游乐场,我可以对每个小节做负数或正数,但不能对一个小节同时做。

https://jsbin.com/dufonoceja/1/edit?js,输出

标签: chart.js

解决方案


这可以从Chart.js v2.9.0 开始,现在支持浮动条。现在可以使用语法指定单个条形图[min, max]

<html>
<head>
    <title>Floating Bars</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
    <style>
        canvas {
            -moz-user-select: none;
            -webkit-user-select: none;
            -ms-user-select: none;
        }
    </style>
</head>

<body>
    <div>
        <canvas id="canvas" height="120"></canvas>
    </div>
    <script>
    
      var chartData = {
      labels: [1,2,3,4,5,6],
      datasets: [{
        type: 'bar',
        label: 'Red Bar',
        borderColor: 'black',
        borderWidth: 1,
        backgroundColor: 'rgba(128,0,0,0.2)',
        data: [[0, 100], [-100, 100], [-30, 40], 0, 0, 0],
      }, {
        type: 'bar',
        label: 'Green Bar',
        backgroundColor: 'rgba(0,128,0,0.2)',   
        borderColor: 'black',
        borderWidth: 1,
        data: [0, 0, 0, 0, [-50, 70], 100],
      }
     ]
    };
      
      window.onload = function() {
            var ctx = document.getElementById('canvas').getContext('2d');
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: chartData,
                options: {
                  scaleBeginAtZero: false,
                  responsive: true,
                  spanGaps: true,
                  tooltips: {
                    mode: 'index',
                    intersect: true
                  },
                  scales: {
                    xAxes: [{                      
                      gridLines: {
                        display: false
                      },
                    }],
                    yAxes: [{
                      type: 'linear',
                      ticks: {
                        beginAtZero: false,
                        min:-100,
                        max:100,
                        stepSize:30
                      }
                    }],
                  }
                }
            });
        };
    </script>
</body>
</html>


推荐阅读