使用类型时,chartjs上的条形图会叠加:'time'

时间:2017-07-05 07:57:30

标签: chart.js

我正在尝试建立一个条形图,其中X轴代表时间。

但是,当我使用选项xAxes: [{type: 'time'}]时,条形图开始叠加,形成一个奇怪的渲染。

删除选项时,条形图显示正确,但X轴标签不显示为日期

我错过了什么,还是错误?

演示here

1 个答案:

答案 0 :(得分:1)

看起来mapjs很难在动态x刻度上获得正确的条形宽度。实现所需目标的快速方法是在x轴上使用常规类别比例,并在显示时格式化标签。要做到这一点,options看起来就像;

 options: {
     scales: {
       xAxes: [{
         ticks: {
           userCallback: function(label, index, labels) {
             return moment(label, "YYYYMMDD").format("MMM DD, YYYY");
           },
         },
       }],
     }
   }

userCallback中的ticks函数只需返回一个字符串,以便您可以根据需要对其进行格式化。

 var labels = ["20170601", "20170602", "20170403", "20170503", "20170703", "20170404", "20170504", "20170704", "20170405", "20170505", "20170605", "20170705", "20170406", "20170606", "20170607", "20170608", "20170509", "20170609", "20170510", "20170511", "20170412", "20170512", "20170612", "20170413", "20170613", "20170414", "20170614", "20170515", "20170615", "20170516", "20170616", "20170517", "20170418", "20170518", "20170419", "20170519", "20170619", "20170420", "20170620", "20170421", "20170621", "20170522", "20170622", "20170523", "20170623", "20170424", "20170524", "20170425", "20170426", "20170526", "20170626", "20170427", "20170627", "20170328", "20170428", "20170628", "20170329", "20170529", "20170629", "20170330", "20170530", "20170630", "20170331", "20170531"],
   values = [5.79, 7.41, 7.08, 7.25, 7.46, 6.79, 7.01, 5.38, 7.35, 7.4, 7.1, 0.49, 7.57, 5.63, 4.15, 7.32, 5.55, 5, 3.26, 6.78, 2.75, 7.27, 7.33, 5.69, 7.1, 7.28, 6.85, 7.27, 6.4, 6.8, 6.9, 7.19, 3.97, 7.11, 6.89, 6.6, 4.03, 7.11, 5.49, 5.31, 2.43, 6.09, 6.14, 5.4, 3.7, 7.13, 5.72, 5.56, 5.4, 7.18, 7.08, 7.19, 7.39, 5.38, 6.96, 7.16, 5.34, 7.21, 5.98, 7.05, 7.32, 3.23, 6.88, 6.86];

 var ctx = document.getElementById("chart");
 var myChart = new Chart(ctx, {
   type: 'bar',
   data: {
     labels: labels,
     datasets: [{
       label: "Time",
       data: values,
     }]
   },
   options: {
     scales: {
       xAxes: [{
         ticks: {
           userCallback: function(label, index, labels) {
             return moment(label, "YYYYMMDD").format("MMM DD, YYYY");
           },
         },
       }],
     }
   }
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<div id="chart-wrapper">
  <canvas id="chart"></canvas>
</div>