简体   繁体   中英

ChartJS Bar chart with time scale - Bars overlap with each other

I'm trying to create a ChartJs Bar chart which contains date on labels.

The chart bars over lap with each other unevenly. Works well when the time scale is removed however, the labels are not date sorted. The labels and data are dynamically populated, so cannot sort it before rendering.

Below is the sample image,

在此处输入图像描述

And, if the scales (xAxis) is removed, it give proper output (but not sorted)

在此处输入图像描述

example: https://codepen.io/karthikkbala/pen/QWjVQqb

Sample data:

[ "2020-05-13", "2020-05-11", "2020-05-12", "2020-05-14", "2020-05-09", "2020-05-10", ] 
[ 20, 11, 9, 22, 11, 9, ]

You can omit labels in the chart configuration and instead generate data as individual points through objects containing x and y properties as shown here.

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] }));

This produces the following 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 }
]

The xAxis would then have to be defined as follows:

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

Please have a look at your amended code below.

 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM