【问题标题】:Chart.js v3: Tooltip callback doesn't identify clicked dataset of stacked bar chartChart.js v3:工具提示回调无法识别堆叠条形图的点击数据集
【发布时间】:2021-07-24 22:32:25
【问题描述】:

在 Chart.js v2 中,ChartTooltipItem[] 的 datasetIndex 属性标识了单击堆叠条形图的哪个部分。这允许为堆积条形图的每个部分自定义工具提示内容。

在 v3 中,TooltipItem[] 提供数据集,但不识别点击了哪个数据集。每个 TooltipItem 都有一个 datasetIndex 字段,但它只是匹配 TooltipItem[] 中的索引,而不是识别点击的片段。

有没有人在 V3 工具提示回调中找到一个字段来确定单击了堆叠条形图的哪个部分?还是在 v3 重写中丢失了这个功能?

【问题讨论】:

    标签: javascript chart.js stacked-chart


    【解决方案1】:

    它工作正常,唯一不同的是它似乎在 v2 中默认为point 模式,而现在它使用index 模式,如果你将它改回point 它可以工作正如预期的那样:

    var options = {
      type: 'bar',
      data: {
        labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
        datasets: [{
            label: '# of Votes',
            data: [12, 19, 3, 5, 2, 3],
            backgroundColor: 'red'
          },
          {
            label: '# of Points',
            data: [7, 11, 5, 8, 3, 7],
            backgroundColor: 'blue'
          }
        ]
      },
      options: {
        plugins: {
          tooltip: {
            mode: 'point',
            callbacks: {
              beforeBody: (ttItems, x) => {
                ttItems.forEach((ttItem) => {
                  console.log('BeforeBody: ', ttItem.datasetIndex, ttItem.dataIndex)
                })
              },
              afterBody: (ttItems, x) => {
                ttItems.forEach((ttItem) => {
                  console.log('AfterBody: ', ttItem.datasetIndex, ttItem.dataIndex)
                })
              }
            }
          }
        },
        scales: {
          y: {
            stacked: true
          },
          x: {
            stacked: true
          }
        }
      }
    }
    
    var ctx = document.getElementById('chartJSContainer').getContext('2d');
    new Chart(ctx, options);
    <body>
      <canvas id="chartJSContainer" width="600" height="400"></canvas>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.4.1/chart.js"></script>
    </body>

    【讨论】:

    • 非常感谢,LeeLenalee!!!这解决了问题。
    猜你喜欢
    • 2019-10-03
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    相关资源
    最近更新 更多