Start bar-chart at 0 using ChartJS

丶灬走出姿态 提交于 2020-01-15 07:01:29

问题


I have a bar chart which use ChartJS that shows data. Based on the bar chart, I have the data: 15, 2, 0, 11.

I can see all of these data in the bar, except 0. Is there a possibility to start the bar chart on 0, so I can also see the data for the fourth column in the bar chart?

options: {
  legend: { display: false },
  scales: {
      yAxes: [{
          display: false,
      }],
      xAxes: [{
          display: true,
      }],
  },
  title: {
    display: false,
  }

}

回答1:


After hours of working, finally i found a soulution. There is no chartjs configuration to do it and you have to draw it your self. Let do it in onComplete function

var ctx = document.getElementById("myChart").getContext('2d');
var datasets = [15, 2, 0, 11];
var myChart = new Chart(ctx, {
  type: 'bar',
  data: {
    labels: ["1", "2", "3", "4"],
    datasets: [{
      label: 'value',
      backgroundColor: '#F00',
      data: datasets
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    },
    animation: {
      onComplete: function() {
        var dataSet = myChart.getDatasetMeta(0);
        dataSet.data.forEach(elm => { 
          if (datasets[elm._index] == 0) {
            ctx.fillStyle = '#F00';
            ctx.fillRect(elm._model.x - elm._view.width / 2, elm._model.y - 1, elm._view.width, 2);
          }
        })
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<canvas class="canvasChart" id="myChart"></canvas>



回答2:


Because your Y-axis values starts from 0 to something. So, if your value is 0 in X-Axis than it would be null and won't show you bar of 0. So, if you want 0 to appear in chart your starting point should be less than the 0.




回答3:


You can try beginAtZero:true config option.

options: {
  legend: { display: false },
  scales: {
      yAxes: [{
          display: false,
          ticks: {
                beginAtZero:true
            }
      }],
      xAxes: [{
          display: true,
      }],
  },
  title: {
    display: false,
  }
}



回答4:


I believe you said you were using chartsjs. This question already has an answer here.



来源:https://stackoverflow.com/questions/44857615/start-bar-chart-at-0-using-chartjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!