如何在chart.js中显示每个切片的饼图数据值 [英] How to display pie chart data values of each slice in chart.js

查看:2784
本文介绍了如何在chart.js中显示每个切片的饼图数据值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Chart.js在我的php页面绘制饼图。我发现工具提示显示每个切片值。



但我希望显示这些值,如下图所示。



我不知道如何使用chart.js。



请帮助我。



我的Javascript代码:

  function drawPie(canvasId,data,legend){
var ctx = $(#pie-canvas-+ canvasId).get(0).getContext(2d);

var piedata = [];
$ .each(data,function(i,val){
piedata.push({value:val.count,color:val.color,label:val.status});
});
var options =
{
tooltipTemplate:<%= Math.round(circumference / 6.283 * 100)%>%,
}
var pie = new Chart(ctx).Pie(piedata,options);
if(legend)document.getElementById(legend)。innerHTML = pie.generateLegend();
}

php代码:

  printf('< table>< tr>'); 
echo'< td style =text-align:right;>< canvas id =pie-canvas-'
。$ canvasId
。'width = height =256>< / canvas>< / td>< td style =text-align:left; width:360px; height:autoid =legendclass =chart-legend >< / td>< / tr>< / table>';

echo'< script type =text / javascript> drawPie('
。$ canvasId
。','
。$ data3
。','
。$ legend
。');< / script>';


<我从什么我知道我不相信Chart.JS有任何功能,以帮助在饼图上绘制文本。但这并不意味着你不能在本机JavaScript中自己做。我将给你一个例子,如何做,下面是为饼图中的每个段绘制文本的代码:

  function drawSegmentValues()
{
for(var i = 0; i< myPieChart.segments.length; i ++)
{
//文本的默认属性)
ctx.fillStyle =white;
var textSize = canvas.width / 10;
ctx.font = textSize +px Verdana;

//获取需要的变量
var value = myPieChart.segments [i] .value;
var startAngle = myPieChart.segments [i] .startAngle;
var endAngle = myPieChart.segments [i] .endAngle;
var middleAngle = startAngle +((endAngle - startAngle)/ 2);

//计算文本位置
var posX =(radius / 2)* Math.cos(middleAngle)+ midX;
var posY =(radius / 2)* Math.sin(middleAngle)+ midY;

//文本中间的文本
var w_offset = ctx.measureText(value).width / 2;
var h_offset = textSize / 4;

ctx.fillText(value,posX - w_offset,posY + h_offset);
}
}

饼形图具有存储在 PieChart.segments ,我们可以看看 startAngle endAngle 的这些段以确定文本将 middleAngle 之间的角度。然后,我们将沿 Radius / 2 的方向移动到图表的中间点,以弧度表示。



在上面的示例中,由于 fillText()是右上角,我们需要得到一些偏移值来纠正。最后 textSize 是根据图表本身的大小确定的,图表越大,文本越大。



小提示范例






通过稍微修改,您可以将数据集的离散数值更改为图形中的百分位数。为此,请获取数据集中各项的总计,调用 totalValue 。然后在每个段上,您可以通过执行以下操作找到百分比:

  Math.round(myPieChart.segments [i] .value / totalValue * 100)+'%'; 

此处 myPieChart.segments [i] .value / totalValue 是计算图表中细分受众群占用的百分比。例如,如果当前段的值为 50 ,且totalValue 200 。然后该段占用的百分比将是: 50/200 => 0.25 。其余的是使这看起来不错。 0.25 * 100 => 25 ,那么我们在结尾处添加。对于整数百分比拼块我舍入到最接近的整数,虽然可以导致精度问题。如果我们需要更高的精度,你可以使用 .toFixed(n)来保存小数位。例如,我们可以在需要时保存一个小数位:

  var value = myPieChart.segments [i] .value / totalValue * 100; 
if(Math.round(value)!== value)
value =(myPieChart.segments [i] .value / totalValue * 100).toFixed(1);
value = value +'%';




I am using Chart.js for drawing pie chart in my php page.I found tooltip as showing each slice values.

But I wish to display those values like below image.

I do not know how to do this with chart.js.

Please help me.

My Javascript code:

function drawPie(canvasId,data,legend){
    var ctx = $("#pie-canvas-" + canvasId).get(0).getContext("2d");

    var piedata = [];
    $.each(data,function(i,val){
        piedata.push({value:val.count,color:val.color,label:val.status});
    });
    var options =
    {
        tooltipTemplate: "<%= Math.round(circumference / 6.283 * 100) %>%",
    }
    var pie = new Chart(ctx).Pie(piedata,options);
    if(legend)document.getElementById("legend").innerHTML = pie.generateLegend();
}

php code:

printf('<table><tr>');
echo '<td style="text-align: right;"><canvas id="pie-canvas-'
    . $canvasId
    . '" width="256" height="256" ></canvas></td><td style="text-align: left;width:360px;height:auto" id="legend" class="chart-legend"></td></tr></table>';

     echo '<script type="text/javascript">drawPie('
    . $canvasId
    . ', '
    . $data3
    .', '
    . $legend
    . ');</script>';

解决方案

From what I know I don't believe that Chart.JS has any functionality to help for drawing text on a pie chart. But that doesn't mean you can't do it yourself in native JavaScript. I will give you an example on how to do that, below is the code for drawing text for each segment in the pie chart:

function drawSegmentValues()
{
    for(var i=0; i<myPieChart.segments.length; i++) 
    {
        // Default properties for text (size is scaled)
        ctx.fillStyle="white";
        var textSize = canvas.width/10;
        ctx.font= textSize+"px Verdana";

        // Get needed variables
        var value = myPieChart.segments[i].value;
        var startAngle = myPieChart.segments[i].startAngle;
        var endAngle = myPieChart.segments[i].endAngle;
        var middleAngle = startAngle + ((endAngle - startAngle)/2);

        // Compute text location
        var posX = (radius/2) * Math.cos(middleAngle) + midX;
        var posY = (radius/2) * Math.sin(middleAngle) + midY;

        // Text offside to middle of text
        var w_offset = ctx.measureText(value).width/2;
        var h_offset = textSize/4;

        ctx.fillText(value, posX - w_offset, posY + h_offset);
    }
}

A Pie Chart has an array of segments stored in PieChart.segments, we can look at the startAngle and endAngle of these segments to determine the angle in between where the text would be middleAngle. Then we would move in that direction by Radius/2 to be in the middle point of the chart in radians.

In the example above some other clean-up operations are done, due to the position of text drawn in fillText() being the top right corner, we need to get some offset values to correct for that. And finally textSize is determined based on the size of the chart itself, the larger the chart the larger the text.

Fiddle Example


With some slight modification you can change the discrete number values for a dataset into the percentile numbers in a graph. To do this get the total value of the items in your dataset, call this totalValue. Then on each segment you can find the percent by doing:

Math.round(myPieChart.segments[i].value/totalValue*100)+'%';

The section here myPieChart.segments[i].value/totalValue is what calculates the percent that the segment takes up in the chart. For example if the current segment had a value of 50 and the totalValue was 200. Then the percent that the segment took up would be: 50/200 => 0.25. The rest is to make this look nice. 0.25*100 => 25, then we add a % at the end. For whole number percent tiles I rounded to the nearest integer, although can can lead to problems with accuracy. If we need more accuracy you can use .toFixed(n) to save decimal places. For example we could do this to save a single decimal place when needed:

var value = myPieChart.segments[i].value/totalValue*100;
if(Math.round(value) !== value)
    value = (myPieChart.segments[i].value/totalValue*100).toFixed(1);
value = value + '%';

Fiddle Example of percentile with decimals

Fiddle Example of percentile with integers

这篇关于如何在chart.js中显示每个切片的饼图数据值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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