简体   繁体   中英

Chart.js bubble chart changing dataset labels

Is it possible to change the dataset labels that show up in the tooltip for a bubble chart.js chart?

图表.js

As it stands right now, the dataset is based off the x,y,r values, but I'd like to inject some additional content, so that instead of reading (5,55,27.5) it reads something like: (Day:5, Total:55) . I'd like to leave off the radius of 27.5 in the tooltip.

Yes! It is possible.

To achieve that, you can use the following tooltip­ 's label callback function :

tooltips: {
   callbacks: {
      label: function(t, d) {
         return d.datasets[t.datasetIndex].label + 
                ': (Day:' + t.xLabel + ', Total:' + t.yLabel + ')';
      }
   }
}

ᴡᴏʀᴋɪɴɢ ᴇxᴀᴍᴘʟᴇ

 var chart = new Chart(ctx, { type: 'bubble', data: { datasets: [{ label: 'Bubble', data: [{ x: 5, y: 55, r: 27.5 }], backgroundColor: 'rgba(0, 119, 290, 0.6)' }] }, options: { tooltips: { callbacks: { label: function(t, d) { return d.datasets[t.datasetIndex].label + ': (Day:' + t.xLabel + ', Total:' + t.yLabel + ')'; } } } } }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script> <canvas id="ctx"></canvas> 

The previous answer doesn't work as of Chart.JS V3 because of these changes: https://github.com/chartjs/Chart.js/blob/master/docs/migration/v3-migration.md 图片显示了来自 https://github.com/chartjs/Chart.js/blob/master/docs/migration/v3-migration.md 的 v2 和 v3 之间的重大变化

The following code works in 4.1.1:

 var chart = new Chart(ctx, { type: 'bubble', data: { datasets: [{ label: 'Bubble', data: [{ x: 5, y: 55, r: 27.5 }], backgroundColor: 'rgba(0, 119, 290, 0.6)' }] }, options: { plugins: { tooltip: { callbacks: { label: function(item) { return item.raw.r } } } } } });
 <script src="https://npmcdn.com/chart.js@latest/dist/chart.umd.js"></script> <canvas id="ctx"></canvas>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM