简体   繁体   English

Chart.js-在不使用工具提示的情况下向气泡图元素添加文本/标签?

[英]Chart.js - Add text/label to bubble chart elements without using tooltips?

Question

Is there any way to add labels to the individual bubbles in a Chart.js bubble chart without resorting to displaying tooltips at all times? 有什么方法可以向Chart.js气泡图中的各个气泡添加标签,而无需始终显示工具提示?

Background 背景

The chart data is for visualizing our project backlog. 图表数据用于可视化我们的项目积压。 Additional details, ie Project Name, about each project are in a table. 有关每个项目的其他详细信息,即项目名称,在表中。

We previously used google charts, and just included the row number from the table on the bubble so you could match things up. 我们以前使用过Google图表,只是在气泡表中包括了表格中的行号,因此您可以进行匹配。 在此处输入图片说明

With Chart.js I only get the bubbles and tooltips. 使用Chart.js我只能得到提示和工具提示。 在此处输入图片说明

I've reviewed the following related questions, but the solution they suggested requires having tooltips display at all times. 我已经审查了以下相关问题,但是他们建议的解决方案要求始终显示工具提示。 I've got a lot more information in the tooltips and displaying them all the time would significantly clutter the chart. 我在工具提示中提供了更多信息,并且始终显示它们会严重干扰图表。

Chart.js doesn't support this directly, but Evert Timberg was very helpful in providing an example Chart.js plugin does exactly this. Chart.js不直接支持此功能,但是Evert Timberg在提供示例Chart.js插件方面确实非常有帮助。

From Chart.js Data Labeling Example Chart.js数据标签示例

// Define a plugin to provide data labels
Chart.plugins.register({
  afterDatasetsDraw: function(chartInstance, easing) {
    // To only draw at the end of animation, check for easing === 1
    var ctx = chartInstance.chart.ctx;
    chartInstance.data.datasets.forEach(function (dataset, i) {
      var meta = chartInstance.getDatasetMeta(i);
      if (!meta.hidden) {
        meta.data.forEach(function(element, index) {
          // Draw the text in black, with the specified font
          ctx.fillStyle = 'rgb(0, 0, 0)';
          var fontSize = 16;
          var fontStyle = 'normal';
          var fontFamily = 'Helvetica Neue';
          ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);
          // Just naively convert to string for now
          // <---- ADJUST TO DESIRED TEXT --->
          var dataString = dataset.data[index].toString();
          // Make sure alignment settings are correct
          ctx.textAlign = 'center';
          ctx.textBaseline = 'middle';
          var padding = 5;
          var position = element.tooltipPosition();
          ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
        });
      }
    });
  }
});

For example, if i just passed in "#22" as the text to render, we get this. 例如,如果我只是传递“#22”作为要渲染的文本,我们将得到此结果。

在此处输入图片说明

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

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