Chart.js v2:如何使工具提示始终显示在饼图上?

Dan*_*nny 27 javascript jquery charts pie-chart chart.js

我在Stack Overflow中发现了类似的问题,但是所有这些问题都在一年前和两年前得到了解决.现在Chart.js出现在版本2中,并且许多文档都发生了变化.有人可以帮我展示带有标签的饼图示例 - 或者饼图及其所有片段的工具提示是否可见?

UPDATE

感谢@potatopeelings,他的回答非常适合Chart.js v2.1.

虽然我最初询问如何在饼图上永久显示工具提示,但我找到了一个更好的解决方案:以百分比形式显示值作为标签!它现在在Chart.js v2.1中启用了饼图.在图表选项中:

animation: {
  duration: 0,
  onComplete: function () {
    var self = this,
        chartInstance = this.chart,
        ctx = chartInstance.ctx;

    ctx.font = '18px Arial';
    ctx.textAlign = "center";
    ctx.fillStyle = "#ffffff";

    Chart.helpers.each(self.data.datasets.forEach(function (dataset, datasetIndex) {
        var meta = self.getDatasetMeta(datasetIndex),
            total = 0, //total values to compute fraction
            labelxy = [],
            offset = Math.PI / 2, //start sector from top
            radius,
            centerx,
            centery, 
            lastend = 0; //prev arc's end line: starting with 0

        for (var val of dataset.data) { total += val; } 

        Chart.helpers.each(meta.data.forEach( function (element, index) {
            radius = 0.9 * element._model.outerRadius - element._model.innerRadius;
            centerx = element._model.x;
            centery = element._model.y;
            var thispart = dataset.data[index],
                arcsector = Math.PI * (2 * thispart / total);
            if (element.hasValue() && dataset.data[index] > 0) {
              labelxy.push(lastend + arcsector / 2 + Math.PI + offset);
            }
            else {
              labelxy.push(-1);
            }
            lastend += arcsector;
        }), self)

        var lradius = radius * 3 / 4;
        for (var idx in labelxy) {
          if (labelxy[idx] === -1) continue;
          var langle = labelxy[idx],
              dx = centerx + lradius * Math.cos(langle),
              dy = centery + lradius * Math.sin(langle),
              val = Math.round(dataset.data[idx] / total * 100);
          ctx.fillText(val + '%', dx, dy);
        }

    }), self);
  }
},
Run Code Online (Sandbox Code Playgroud)

Fl0*_*D3R 28

ChartJs版本> 2.1.5的解决方案:

Chart.pluginService.register({
  beforeRender: function (chart) {
    if (chart.config.options.showAllTooltips) {
        // create an array of tooltips
        // we can't use the chart tooltip because there is only one tooltip per chart
        chart.pluginTooltips = [];
        chart.config.data.datasets.forEach(function (dataset, i) {
            chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                chart.pluginTooltips.push(new Chart.Tooltip({
                    _chart: chart.chart,
                    _chartInstance: chart,
                    _data: chart.data,
                    _options: chart.options.tooltips,
                    _active: [sector]
                }, chart));
            });
        });

        // turn off normal tooltips
        chart.options.tooltips.enabled = false;
    }
},
  afterDraw: function (chart, easing) {
    if (chart.config.options.showAllTooltips) {
        // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
        if (!chart.allTooltipsOnce) {
            if (easing !== 1)
                return;
            chart.allTooltipsOnce = true;
        }

        // turn on tooltips
        chart.options.tooltips.enabled = true;
        Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
            tooltip.initialize();
            tooltip.update();
            // we don't actually need this since we are not animating tooltips
            tooltip.pivot();
            tooltip.transition(easing).draw();
        });
        chart.options.tooltips.enabled = false;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 谢谢!在2.4.0中,它已更改为Chart.plugins.register (4认同)

pot*_*ngs 15

使用新的Chart.js 2.1,您可以编写一个插件来执行此操作并通过options属性控制它


预习

在此输入图像描述


脚本

请注意,您需要在初始化图表之前注册插件

Chart.pluginService.register({
    beforeRender: function (chart) {
        if (chart.config.options.showAllTooltips) {
            // create an array of tooltips
            // we can't use the chart tooltip because there is only one tooltip per chart
            chart.pluginTooltips = [];
            chart.config.data.datasets.forEach(function (dataset, i) {
                chart.getDatasetMeta(i).data.forEach(function (sector, j) {
                    chart.pluginTooltips.push(new Chart.Tooltip({
                        _chart: chart.chart,
                        _chartInstance: chart,
                        _data: chart.data,
                        _options: chart.options,
                        _active: [sector]
                    }, chart));
                });
            });

            // turn off normal tooltips
            chart.options.tooltips.enabled = false;
        }
    },
    afterDraw: function (chart, easing) {
        if (chart.config.options.showAllTooltips) {
            // we don't want the permanent tooltips to animate, so don't do anything till the animation runs atleast once
            if (!chart.allTooltipsOnce) {
                if (easing !== 1)
                    return;
                chart.allTooltipsOnce = true;
            }

            // turn on tooltips
            chart.options.tooltips.enabled = true;
            Chart.helpers.each(chart.pluginTooltips, function (tooltip) {
                tooltip.initialize();
                tooltip.update();
                // we don't actually need this since we are not animating tooltips
                tooltip.pivot();
                tooltip.transition(easing).draw();
            });
            chart.options.tooltips.enabled = false;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

然后

new Chart(ctx, {
    type: 'pie',
    data: data,
    options: {
        showAllTooltips: true
        ...
Run Code Online (Sandbox Code Playgroud)

使用较旧的2.x版本,您应该能够将相同的(或类似的,我不确定早期的数据结构)移动到 options.animation.onComplete


小提琴 - http://jsfiddle.net/q15ta78q/

  • 我正在使用charts.js 2.2.1,如果您将`_options:chart.options`更改为`_options:chart.options.tooltips`,则此方法有效 - (5认同)

ind*_*ull 13

我正在寻找类似的解决方案,并遇到了这个chartjs插件Chart.PieceLabel.js.它具有显示标签,值和百分比等模式的配置.

  • 这个插件在循环中泛滥。它有效,但滞后很多。 (2认同)