ChartJS 垂直条形图 - 根据指定的最大值测量每列中数据的百分比

ChartJS vertical bar chart - measure percentage of the data in each column based on a specified max

我希望我的标题足够好,我是 chartJS 的新手,实际上我刚刚开始我多次阅读整个文档并完成了许多简单到中等难度的示例。

我正在尝试按类别绘制测试结果图表,例如数学测试包括以下类别:代数、微积分、分析、几何、组合数学。我正在制作一个图表,其中每个 bar/column 是一个类别,数据是来自该类别的正确问题的数量,作为我的最大值 bar/column 我想在一个中拥有最大数量的问题给定类别,所以无论我插入什么数字,这个数字将始终是我的最大值,所以 100%,所以如果我在测试中有 10 个代数问题并且我正确回答 7/10,我希望看到 bar 是 70%,因为这是这个特定类别的正确问题数量,但如果我在微积分中有 4/10,这个特定 bar/column 应该是 40%。

我希望我的解释足够清楚,我已经准备好实现这一目标所需的所有数据,但无论我研究多少,我都不知道如何准确执行。

如有任何帮助或指出正确的方向,我们将不胜感激!

解决方案在很大程度上取决于基础数据的格式。例如,它可以定义如下:

const testResults = [
  { category: 'Algebra', totalQuestions: 10, correclyAnswered: 7 },
  { category: 'Calculus', totalQuestions: 12, correclyAnswered: 9 },
  { category: 'Analysis', totalQuestions: 8, correclyAnswered: 5 },
  { category: 'Geometry ', totalQuestions: 10, correclyAnswered: 10 },
  { category: 'Combinatorics ', totalQuestions: 9, correclyAnswered: 5 }
];

在这种情况下,图表 data 可以通过以下方式生成:

const data = {
  labels: testResults.map(o => o.category),
  datasets: [
    {
      label: 'Test Results',
      backgroundColor: 'rgba(0, 255, 0, 0.2)',
      borderColor: 'rgba(0, 255, 0)',
      borderWidth: 1,
      data: testResults.map(o => (100 / o.totalQuestions * o.correclyAnswered))
    }
  ]
};

然后您还必须定义图表 options 以确保工具提示和标签的格式正确并且 x 轴在 0 到 100 % 之间展开。

const options = {      
  tooltips: {
    callbacks: {
      label: (tooltipItem, data) => {
        var label = data.datasets[tooltipItem.datasetIndex].label || '';
        return label + ': ' + tooltipItem.xLabel.toFixed(0) + '%';
      }
    }
  },
  scales: {
    xAxes: [{
      ticks: {
        min: 0,
        max: 100,
        stepSize: 10,
        callback: value => value + '%'
      } 
    }]
  }
}

图表本身定义如下:

<HorizontalBar 
  data = { data } 
  options = { options } 
/>

请看这个StackBlitz