Chart.js条形图显示为空白,数据集较小

j5fpnvbx  于 2023-10-18  发布在  Chart.js
关注(0)|答案(1)|浏览(192)
new Chart(
    document.getElementById('chart'),
    {
        type: 'bar',
        data: {
            datasets: [
                {
                    label: 'Conversions',
                    data: [0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
                }
            ]
        },
        options: {
            maintainAspectRatio: false,
            scales: {
                y: {
                    beginAtZero: true                   
                },
                x: {
                    beginAtZero: true
                }
            }
        }
    }
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.1.1/chart.umd.js"></script>
<canvas id="chart"> </canvas>

我有一个动态加载的Chart.js条形图。根据数据的不同,图表将是空白的,即使有数据要显示。下面是图表示例化的一个示例,其中数据变量被创建一个空白图表的示例输入替换。数据较少的图表似乎更有可能显示空白。出什么事了?

wmomyfyw

wmomyfyw1#

你在数据中遗漏了标签数组。您必须定义标签(相同长度的数据)。你可以看到结果。(提示:我建议将maintainAspectRatio设置为true
下面是工作示例:

const data = [0,0,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

const charts = document.getElementById("chart1");
  new Chart(
    charts,
    {
      type: 'bar',
      data: {
        labels: Array.from('x'.repeat(data.length-1)), // you can five any labels array you want
        datasets: [
          {
            label: 'Conversions',
            data: data
          }
        ]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true,
            suggestedMin: 0,
            suggestedMax: 1
          },
        }
      }
    }
  );

相关问题