简体   繁体   English

Chart.js Treemap 向每个矩形添加自定义文本

[英]Chart.js Treemap Adding custom text to each rectangle

I am using chart.js to develop a TreeMap.我正在使用 chart.js 开发 TreeMap。 It works great but the issue is each rectangle only shows the value of the data.它很好用,但问题是每个矩形只显示数据的值。 I want to add some custom text next to the value.我想在值旁边添加一些自定义文本。 How do I achieve this?我如何实现这一目标?

var topTags = [
  {tag:'python',num:133269},{tag:'javascript',num:109742},{tag:'java',num:65490},{tag:'c#',num:45445},{tag:'html',num:43767},{tag:'android',num:42657},{tag:'reactjs',num:38844},{tag:'php',num:34381},{tag:'sql',num:29996},{tag:'python',num:29942},{tag:'css',num:29654},{tag:'r',num:28319},{tag:'c++',num:27389},{tag:'node.js',num:25415},{tag:'angular',num:24093},{tag:'pandas',num:23826},{tag:'arrays',num:23075},{tag:'jquery',num:18968},{tag:'mysql',num:18863},{tag:'swift',num:17971},{tag:'ios',num:17600},{tag:'json',num:15589},{tag:'laravel',num:15537},{tag:'flutter',num:15201},{tag:'c',num:15195},{tag:'django',num:14748},{tag:'sql',num:12752},{tag:'reactjs',num:10974},{tag:'excel',num:10962},{tag:'list',num:10726},{tag:'regex',num:10676}
];

var canvas = document.getElementById("treemap");
var ctx = canvas.getContext("2d");
var chart = window.chart = new Chart(ctx, {
  type: "treemap",
  data: {
    datasets: [{
      tree: topTags,
      key: "num",
      groups: ['num'],
      spacing: 0.5,
      borderWidth: 1.5,
      fontColor: "black",
      borderColor: "grey"
    }]
  },
  options: {
    maintainAspectRatio: false,
    legend: { display: false },
    tooltips: { enabled: false }
  }
});

When running this code, I get the numbers in each rectangle but I need some text to be appended next to the numbers for each rectangle.运行此代码时,我得到每个矩形中的数字,但我需要在每个矩形的数字旁边附加一些文本。 How do I achieve this?我如何实现这一目标?

You can use the formatter options in the labels section:您可以使用labels部分中的formatter选项:

 const options = { type: 'treemap', data: { datasets: [{ label: '# of Votes', tree: [12, 19, 3, 5, 2, 3], backgroundColor: 'pink', labels: { display: true, formatter(ctx) { const data = ctx.chart.data; return `Custom Text: ${data.datasets[ctx.datasetIndex].tree[ctx.dataIndex]}`; } }, }] }, options: {} } const 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.7.0/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/chartjs-chart-treemap@2.0.1/dist/chartjs-chart-treemap.js"></script> </body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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