【问题标题】:How do I display a different chartjs tooltip title?如何显示不同的 chartjs 工具提示标题?
【发布时间】:2021-01-16 21:08:25
【问题描述】:

我正在使用 chartjs 显示混合条形图和折线图。当您将鼠标悬停在折线图或条形图上时,我已成功地在工具提示中显示不同的内容,但使用相同的条件无法显示不同的标题:

callbacks: {
  title: function(tooltipItem, data) {                      
     if (tooltipItem.datasetIndex === 0){
       return data['datasets'][0]['label'];
     }else{
       return data['datasets'][1]['label'];  
     }
   }
}

我正在使用 PHP 值将数据填充到主图表中。这是主图表的代码:

var ctx_<?=$chartname?> = document.getElementById('<?=$chartname?>').getContext('2d');
new Chart(ctx_<?=$chartname?>, {
    type: 'bar',
    data: {
        labels: [<?=$labels?>], //label array needs to go here
        datasets: [{
                label: 'Overall Average Score',
                notes: ['','','','',''],
                data: [<?=$averages?>],
                pointBackgroundColor: '#6600CC',
                pointRadius: 6,
                pointBorderColor: 'rgb(255, 255, 255)',    
                pointHoverRadius:8,
                pointHoverBorderWidth: 2,
                pointHoverBorderColor: 'rgb(255, 255, 255)', 
                fill: false,
                
                // Changes this dataset to become a line
                type: 'line'
            },{
                label: '<?=$forename?>\'s Score',
                notes: [<?=$notes?>],
                data: [<?=$scores?>] //data array needs to go in here
            }],
    },
    options: groupBarChartOptions
});

但是,它不是将工具提示标题填充为“总体平均分数”,而是填充折线图工具提示标题“学生姓名的分数”

我用的是同款

if (tooltipItem.datasetIndex === 0){

下面的标签回调中的条件,它可以工作。

【问题讨论】:

    标签: javascript chart.js


    【解决方案1】:

    这应该可以满足您的需求:

    title: (tooltipItem, data) => {
        return data['datasets'][tooltipItem[0].datasetIndex]['label']
    }
    

    工作示例:https://jsfiddle.net/Leelenaleee/bcwky40z/4/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多