ChartJS带时间刻度的条形图-条形相互重叠

问题描述 投票:0回答:1

我正在尝试创建一个ChartJs条形图,其中的标签上包含日期。

图表彼此之间的搭接不均匀。删除时间刻度后,效果很好,但是标签未按日期排序。标签和数据是动态填充的,因此在渲染之前无法对其进行排序。

下面是示例图像,

enter image description here

而且,如果刻度(xAxis)被删除,它会提供正确的输出(但不排序)

enter image description here

示例:https://codepen.io/karthikkbala/pen/QWjVQqb

样本数据:

[ "2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10", ] 
[ 20, 11, 9, 22, 11, 9, ]
javascript charts chart.js bar-chart
1个回答
0
投票

您可以在图表配置中省略labels,而是通过包含datapoints属性的对象生成x作为单独的y,如下所示。

const labels = ["2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10"];
const baseData = [20, 11, 9, 22, 11, 9];
const data = labels.map((l, i) => ({ x: l, y: baseData[i] }));

这将产生以下data

[
  { "x": "2020-05-13", "y": 20 },
  { "x": "2020-05-11", "y": 11 },
  { "x": "2020-05-12", "y": 9 },
  { "x": "2020-05-14", "y": 22 },
  { "x": "2020-05-09", "y": 11 },
  { "x": "2020-05-10", "y": 9 }
]

xAxis然后必须定义如下:

xAxes: [{
  offset: true,
  type: 'time',
  time: {
    unit: 'day',   
    source: 'data',
    tooltipFormat: 'MMM DD' 
  }
}],

请在下面查看您的修改后的代码。

const labels = ["2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10"];
const baseData = [20, 11, 9, 22, 11, 9];
const data = labels.map((l, i) => ({ x: l, y: baseData[i] }));

var chartData = {
  datasets: [{
    label: "All Detections",
    backgroundColor: "#02a499",
    borderColor: "#ffffff",
    borderWidth: 1,
    hoverBackgroundColor: "#02a499",
    hoverBorderColor: "#02a499",
    data: data
  }]
};

new Chart("ChartByDate", {
  type: 'bar',
  data: chartData,
  options: {
    scales: {
      xAxes: [{
        offset: true,
        type: 'time',
        time: {
          unit: 'day',   
          source: 'data',
          tooltipFormat: 'MMM DD' 
        }
      }],
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
<canvas id="ChartByDate"></canvas>
© www.soinside.com 2019 - 2024. All rights reserved.