Chart.js:如果差异太大,部分板块不显示

uemypmqf  于 2022-11-06  发布在  Chart.js
关注(0)|答案(2)|浏览(157)

我将以下配置传递给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应该已经能够显示所有的部分(为最小的扇区设置最小的大小等)。
是否有一些参数我可以传递给配置来修复这个问题?

mutmk8jj

mutmk8jj1#

您可以使用对数刻度,但只能用于线。对于您的用例,圆环不是一个好的选择
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();
    }
  },
];
7xllpg7q

7xllpg7q2#

一种替代方法是使用3个数据集,每个数据集对应一个数据。

labels: ['a', 'b', 'c'],   
datasets: [
  {
    label: "My First Dataset",
    data: [878,0,0],
    backgroundColor: [
      "rgb(255, 205, 86)",
      "rgb(255, 99, 132)",
      "rgb(54, 162, 235)",          
    ],        
    offset:0,
    hoverOffset: 0,               
  },
  {
    label: "My First Dataset2",
    data: [0,19020,0],
    backgroundColor: [
      "rgb(255, 205, 86)",
      "rgb(255, 99, 132)",
      "rgb(54, 162, 235)",          
    ],        
    offset:0,
    hoverOffset: 0,       

  },
  {
    label: "My First Dataset2",
    data: [0,0,100412286],
    backgroundColor: [
      "rgb(255, 205, 86)",
      "rgb(255, 99, 132)", 
      "rgb(54, 162, 235)",         
    ],        
    offset:0,
    hoverOffset: 0,       

  },
],

我希望这对你有帮助。

相关问题