Chart.js v2:如何使工具提示总是出现在饼图上? [英] Chart.js v2: How to make tooltips always appear on pie chart?

查看:847
本文介绍了Chart.js v2:如何使工具提示总是出现在饼图上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了类似问题在Stack Overflow中,但是所有这些都是在一两年前解决的。现在Chart.js出现在版本2,并且许多文档更改。有人可以帮我显示带有标签的饼图的示例,或者显示其所有细分的工具提示的饼图。



UPDATE / p>

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



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

 动画:{
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 ,//计算分数的总值
labelxy = [],
offset = Math.PI / 2,//从顶部开始扇区
radius,
centerx,
centery,
lastend = 0; // prev arc的结束行:从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);
}
},


解决方案

Chart.js版本> 2.1.5的解决方案:

  Chart.pluginService.register({
beforeRender:function {
if(chart.config.options.showAllTooltips){
//创建一个工具提示数组
//我们不能使用图表工具提示,因为每个图表只有一个工具提示
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));
});
});

//关闭正常的工具提示
chart.options.tooltips.enabled = false;
}
afterDraw:function(chart,easing){
if(chart.config.options.showAllTooltips){
//我们不想永远的工具提示动画,所以不要做任何东西,直到动画运行至少一次
if(!chart.allTooltipsOnce){
if(easing!== 1)
return;
chart.allTooltipsOnce = true;
}

//打开工具提示
chart.options.tooltips.enabled = true;
Chart.helpers.each(chart.pluginTooltips,function(tooltip){
tooltip.initialize();
tooltip.update();
//我们实际上需要这个,因为我们不是动画工具提示
tooltip.pivot();
tooltip.transition(easing).draw();
});
chart.options.tooltips.enabled = false;
}
}
});


I have found similar questions in 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?

UPDATE

Thanks to @potatopeelings, his answer works perfectly for 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:

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

解决方案

Solution for ChartJs Version > 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;
    }
  }
});

这篇关于Chart.js v2:如何使工具提示总是出现在饼图上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆