使用ChartJS从0开始绘制条形图 [英] Start bar-chart at 0 using ChartJS

查看:343
本文介绍了使用ChartJS从0开始绘制条形图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用ChartJS来显示数据的条形图。根据条形图,我得到了数据: 15,2,0,11

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

我可以在条形图中看到所有这些数据,但0除外。有可能将条形图从0开始,因此我也可以看到条形图的第四列?

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,
  }

}


推荐答案

工作了几个小时,终于找到了解决方法。没有chartjs配置可以执行此操作,您必须自己绘制。让我们在 onComplete 函数

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>

这篇关于使用ChartJS从0开始绘制条形图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆