How can I show a subset of data on pie pieces in Chart.JS while still displaying the superset when hovering?

后端 未结 2 1198
猫巷女王i
猫巷女王i 2021-01-16 19:52

I\'ve got a pie chart that looks like this when hovering over a piece of pie:

Except for wanting the legend to the right instead of on top, I\'m fairly cont

2条回答
  •  暖寄归人
    2021-01-16 20:43

    Alright looks like you have some simple syntax errors in your updated code that probably happened with copying over. Ignoring those, you can manage this by creating a function in your animation options. Here is the fiddle. Thanks to Hung Tran's work here.

    animation: {
      duration: 0,
      easing: "easeOutQuart",
      onComplete: function () {
        var ctx = this.chart.ctx;
        ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontFamily, 'normal', Chart.defaults.global.defaultFontFamily);
        ctx.textAlign = 'center';
        ctx.textBaseline = 'bottom';
    
        this.data.datasets.forEach(function (dataset) {
    
          for (var i = 0; i < dataset.data.length; i++) {
            var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model,
                total = dataset._meta[Object.keys(dataset._meta)[0]].total,
                mid_radius = model.innerRadius + (model.outerRadius - model.innerRadius)/2,
                start_angle = model.startAngle,
                end_angle = model.endAngle,
                mid_angle = start_angle + (end_angle - start_angle)/2;
    
            var x = mid_radius * Math.cos(mid_angle);
            var y = mid_radius * Math.sin(mid_angle);
    
            ctx.fillStyle = '#fff';
            if (i == 3){ // Darker text color for lighter background
              ctx.fillStyle = '#444';
            }
            var percent = String(Math.round(dataset.data[i]/total*100)) + "%";
            // this prints the data number
            ctx.fillText(dataset.data[i], model.x + x, model.y + y);
            // this prints the percentage
            ctx.fillText(percent, model.x + x, model.y + y + 15);
          }
        });               
      }
    }
    

提交回复
热议问题