首页 > 解决方案 > Chart.js:如果差异太大,某些部门未显示

问题描述

我将以下配置传递给Chart.js

{
  type: 'doughnut',
  data: {
    labels: ['a', 'b', 'c'],
    datasets: [{
      data: [878, 19020, 100412286],
      backgroundColor: [
        'rgb(255, 99, 132)',
        'rgb(54, 162, 235)',
        'rgb(255, 205, 86)'
      ],
      hoverOffset: 4
    }]
  }
}

但是由于这三个之间的巨大差异(考虑到有多大c),c最终会“重叠”其他所有内容,我只得到一个只有一种颜色的甜甜圈,只显示c.

c如果我尝试为所有三个扇区设置一个较小的值,则显示效果很好。

但我不明白,Chart.js应该能够显示所有部分(为最小扇区设置最小大小等)

是否有一些参数可以传递给配置来解决这个问题?

标签: javascriptchart.js

解决方案


您可以使用对数刻度,但只能用于线条。甜甜圈不是您的用例的好选择

https://www.chartjs.org/docs/latest/samples/scales/log.html

配置:

  const config = {
  type: 'line',
  data: data,
  options: {
    responsive: true,
    plugins: {
      title: {
        display: true,
        text: 'Chart.js Line Chart - Logarithmic'
      }
    },
    scales: {
      x: {
        display: true,
      },
      y: {
        display: true,
        type: 'logarithmic',
      }
    }
  },
};

设置:

const DATA_COUNT = 7;
const NUMBER_CFG = {count: DATA_COUNT, min: 0, max: 100};

const labels = Utils.months({count: 7});
const data = {
  labels: labels,
  datasets: [
    {
      label: 'Dataset 1',
      data: logNumbers(DATA_COUNT),
      borderColor: Utils.CHART_COLORS.red,
      backgroundColor: Utils.CHART_COLORS.red,
      fill: false,
    },
  ]
};

行动

const logNumbers = (num) => {
  const data = [];

  for (let i = 0; i < num; ++i) {
    data.push(Math.ceil(Math.random() * 10.0) * Math.pow(10, Math.ceil(Math.random() * 5)));
  }

  return data;
};

const actions = [
  {
    name: 'Randomize',
    handler(chart) {
      chart.data.datasets.forEach(dataset => {
        dataset.data = logNumbers(chart.data.labels.length);
      });
      chart.update();
    }
  },
];

推荐阅读