Javascript Chart.js v2:如何让工具提示总是出现在饼图上?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36992922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:47:44  来源:igfitidea点击:

Chart.js v2: How to make tooltips always appear on pie chart?

javascriptjquerychartspie-chartchart.js

提问by Danny

I have found similar questionsin Stack Overflow, but all of them were addressed one and two years ago. Now Chart.js has come up in version 2, and lots of the documentation changes. Can someone please help me showing an example of pie chart with labels - or pie chart with all of its segment's tooltips are visible?

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

UPDATE

更新

Thanks to @potatopeelings, his answer works perfectly for Chart.js v2.1.

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

Although I initially asked how to permanently show tooltips on pie chart here, I found a better solution: showing values as labels in percentages! It is now enabled for pie chart in Chart.js v2.1. In the chart options:

虽然我最初在这里询问如何在饼图上永久显示工具提示,但我找到了一个更好的解决方案:将值显示为百分比标签!它现在在 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);
  }
},

回答by Fl0R1D3R

Solution for ChartJs Version > 2.1.5:

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;
    }
  }
});

回答by potatopeelings

With the new Chart.js 2.1 you can write a plugin to do this and control it via an optionsproperty

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



Preview

预览

enter image description here

在此处输入图片说明



Script

脚本

Note that you need to register the plugin before you initialize the chart

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

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;
        }
    }
});

and then

进而

new Chart(ctx, {
    type: 'pie',
    data: data,
    options: {
        showAllTooltips: true
        ...

With the older 2.x version, you should able to move the same (or similar, I'm not sure about the earlier data structure ) to the options.animation.onComplete

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



Fiddle - http://jsfiddle.net/q15ta78q/

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

回答by indusBull

I was looking for similar solution and came across this chartjs plugin Chart.PieceLabel.js. It has configs to display modes like label, value and percentage.

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

回答by jonyB

If you got here because you were looking for a way to make pie charts always look hovered like I was. here is the solution that helped me: https://nobal.in/technology/chart-js/how-to-highlight-selected-in-pie-doughnut/

如果你来到这里是因为你正在寻找一种方法让饼图看起来总是像我一样悬停。这是帮助我的解决方案:https: //nobal.in/technology/chart-js/how-to-highlight-selected-in-pie-doughnut/

I just needed a way to programmatically enlarge one part of the pie chart, and this is exactly it

我只需要一种方法来以编程方式放大饼图的一部分,这正是它

回答by ElllGeeEmm

According to the closed issue on the github page for chart.js, displaying tool tips permanently is not recommended.

根据github页面上chart.js的已关闭问题,不建议永久显示工具提示。

This comment closing this issue gives more detail:

关闭此问题的此评论提供了更多详细信息:

https://github.com/chartjs/Chart.js/issues/1861#issuecomment-442852768

https://github.com/chartjs/Chart.js/issues/1861#issuecomment-442852768

and this is the recommended plugin for permanent data labels:

这是永久数据标签的推荐插件:

https://github.com/chartjs/chartjs-plugin-datalabels

https://github.com/chartjs/chartjs-plugin-datalabels