首页 > 解决方案 > ChartJS Javascript - 如何绘制堆积条形直方图但数据集大小未知

问题描述

我想用 ChartJS 绘制一个堆积条形直方图。我看到了很多代码,而且我一般都知道该怎么做。

就我而言,问题如下:

比方说,我有 30 个与标签(或轴)相对应的日期。

然后对于每个日期,我可能有一个或多个显示特定数据的值。

例如:日期 1 --> [1, 2],日期 2 --> [0.5],日期 3 --> [2, 4, 6, 8] 等。

如何知道数据集的大小会有所不同。

到目前为止,我做了这样的事情:

  var chartdata = {
    labels: [],
    datasets: [{
      data: []
    }, {
      data: []
    }]
  };
  var canva_id = "#" + canvaID
  var ctx = $(canva_id);

  var options = {
    maintainAspectRatio: true,
    tooltips: {
      mode: 'index',
      intersect: false
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true,
        scaleLabel: {
          display: true,
          labelString: 'Date'
        },
        gridLines: {
          display: false
        }
      }],
      yAxes: [{
        stacked: true,
        ticks: {
          beginAtZero: true,
          stepSize: 1
        },
        gridLines: {
          display: false
        },
        scaleLabel: {
          display: true,
          labelString: 'Nb height'
        },

      }]
    },
    legend: {
      display: false
    },
    title: {
      display: true,
      text: ''
    }
  }
  var chartInstance = new Chart(ctx, {
    type: 'bar',
    data: chartdata,
    options: options
  });

 [...]

var color = Array("#6ec72e", "#A77A2F", "#BF1515", "#4C4CAD", "#993366", "#401010");
  //Dict contain the date as a key and the array of data value as a value
  for (const [key, value] of Object.entries(dict)) {

    chartInstance.data.labels[key] = value["date"];
    chartInstance.update();

    var count = 0;
    // create a new dataset with empty values
    var newDataset = {
      data: []
    };
    chartInstance.data.datasets.push(newDataset);

    for (let v = 0; v < value["height"].length; v++) {
      chartInstance.data.datasets[key].backgroundColor = color[v];

      chartInstance.data.datasets[key].data[v] = value["height"][v];

    }

    // Finally, make sure you update your chart, to get the result
    chartInstance.update();

  }

请问有什么帮助吗?

感谢

标签: javascriptplotchart.jshistogram

解决方案


推荐阅读