Cómo agregar etiquetas en el gráfico.js canvas plugin?


Estoy usando el plugin impresionante Gráfico.js, y estoy tratando de encontrar la forma de mostrar etiquetas dentro de cada porcentaje. Así que lo busqué en Google, y encontré esta atracción: https://github.com/nnnick/Chart.js/pull/35

Hice un simple violín para probarlo, pero no funciona: http://jsfiddle.net/marianico2/7ktug/1/

Este es el contenido:

HTML

<canvas id="canvas" height="450" width="450"></canvas>

JS

$(document).ready(function () {
    var pieData = [{
        value: 30,
        color: "#F38630",
        label: 'HELLO',
        labelColor: 'black',
        labelFontSize: '16'
    }, {
        value: 50,
        color: "#E0E4CC"
    }, {
        value: 100,
        color: "#69D2E7"
    }];

    var myPie = new Chart(document.getElementById("canvas").getContext("2d")).Pie(pieData, {
        labelAlign: 'center'
    });
});

Me temo que no hay información sobre esto en la documentación .

También me gustaría saber cómo mostrar una etiqueta para cada porción, pero fuera del gráfico. Unidos por una línea. Al igual que los gráficos de highcharts.js .

Por cierto, me encantaría que me recomiendes una alternativa de gráficos html5 que incluya las opciones que dije anteriormente. He oído hablar del plugin flot , pero me temo que no soporta animaciones...

Si necesita más información, hágamelo saber y editaré el post.

Author: Dennis Rongo, 2013-05-16

4 answers

Tendrás que añadir código en 2 lugares. Como ejemplo, toma el donut. Primero agregue información de etiqueta a los valores predeterminados (mire el gráfico original.código js y comparar con esto):

    chart.Doughnut.defaults = {
        segmentShowStroke : true,
        segmentStrokeColor : "#fff",
        segmentStrokeWidth : 2,
        percentageInnerCutout : 50,
        animation : true,
        animationSteps : 100,
        animationEasing : "easeOutBounce",
        animateRotate : true,
        animateScale : false,
        onAnimationComplete : null,
        labelFontFamily : "Arial",
        labelFontStyle : "normal",
        labelFontSize : 24,
        labelFontColor : "#666"
    };

Luego baja a donde se dibuja la Rosquilla y agrega las cuatro ctx líneas.

    animationLoop(config,null,drawPieSegments,ctx);

    function drawPieSegments (animationDecimal){
        ctx.font = config.labelFontStyle + " " + config.labelFontSize+"px " + config.labelFontFamily;
        ctx.fillStyle = 'black';
        ctx.textBaseline = 'middle';
        ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);

La llamada ctx.fillText pondrá el texto en el lienzo, por lo que puede usarlo para escribir texto con coordenadas x,y. Usted debe ser capaz de utilizar esta manera de hacer etiquetas básicas. Aquí está el jsfiddle to tinker con:

Http://jsfiddle.net/nCFGL / (mira las líneas 281 y 772 en la sección JavaScript del jsfiddle para el código antes mencionado)

Si necesitas algo más elegante, alguien bifurcó una versión de Gráficos.js y añadido tooltips. Aquí está la discusión https://github.com/nnnick/Chart.js/pull/35 , y podrás encontrar el enlace a la versión bifurcada dentro de esa discusión.

 32
Author: Jack,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-20 00:57:05

Este literalmente tomó horas y horas y encontré una solución de trabajo.

Https://github.com/nnnick/Chart.js/pull/116

Este fue mi código final. Estaba tratando de mostrar porcentajes como etiquetas en donut

Chart.types.Doughnut.extend({
name: "DoughnutAlt",
draw: function() {
    Chart.types.Doughnut.prototype.draw.apply(this, arguments);
    this.chart.ctx.fillStyle = 'black';
    this.chart.ctx.textBaseline = 'middle';
    this.chart.ctx.textAlign = 'start';
    this.chart.ctx.font="18px Verdana";

    var total = 0;
    for (var i = 0; i < this.segments.length; i++) { 
        total += this.segments[i].value;      
    }

    this.chart.ctx.fillText(total , this.chart.width / 2 - 20, this.chart.height / 2, 100);
    for(var i = 0; i < this.segments.length; i++){
        var percentage = ((this.segments[i].value / total) * 100).toFixed(1);
        if( percentage > 3 ){
            var centreAngle = this.segments[i].startAngle + ((this.segments[i].endAngle - this.segments[i].startAngle) / 2),
                rangeFromCentre = (this.segments[i].outerRadius - this.segments[i].innerRadius) / 2 + this.segments[i].innerRadius;
            var x = this.segments[i].x + (Math.cos(centreAngle) * rangeFromCentre);
            var y = this.segments[i].y + (Math.sin(centreAngle) * rangeFromCentre);
            this.chart.ctx.textAlign = 'center';
            this.chart.ctx.textBaseline = 'middle';
            this.chart.ctx.fillStyle = '#fff';
            this.chart.ctx.font = 'normal 10px Helvetica';
            this.chart.ctx.fillText(percentage , x, y);
        }
     }
}
});
 7
Author: animesh manglik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-26 09:44:46

Hay una versión bifurcada, ChartNew, que proporciona esta funcionalidad fuera de la caja.

Si necesita usar ChartJS, puede usar esta versión revisada de @Solución de Jack:

Chart.types.Doughnut.extend({
    name: "DoughnutAlt",
    draw: function() {
        Chart.types.Doughnut.prototype.draw.apply(this, arguments);
        this.chart.ctx.fillStyle = 'black';
        this.chart.ctx.textBaseline = 'middle';
        this.chart.ctx.fillText(this.segments[0].value + "%", this.chart.width / 2 - 20, this.chart.width / 2, 200);
    }
});
 3
Author: dunckr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-10 11:00:56

He descubierto una manera para que podamos mostrar los valores para cada región fuera del lado del gráfico.

También eliminé la rotación de los valores y me referí a aquí

Agregue las siguientes líneas de código dentro de la función Donut. (He pegado las líneas modificadas del Gráfico.archivo js).

    var Doughnut = function(data,config,ctx){

    var segmentTotal = 0;

    //In case we have a canvas that is not a square. Minus 10 pixels as padding round the edge.
    var doughnutRadius = Min([height/2,width/2]) - 15;
    var cutoutRadius = doughnutRadius * (config.percentageInnerCutout/100);
    //Modified for setting the label values out side the arc
    var outRadius= doughnutRadius + cutoutRadius/3;
    var outRadiustop= doughnutRadius + cutoutRadius/5;
    ......
    ......
    ......

    function drawPieSegments (animationDecimal){
    :
    :



       if (config.scaleShowValues) {
                ctx.save();                
                ctx.translate(width / 2, height / 2);
                ctx.font = config.scaleFontStyle + ' ' + config.scaleFontSize + 'px ' + config.scaleFontFamily;
                ctx.textBaselne = 'middle';
                var a = (cumulativeAngle + cumulativeAngle + segmentAngle) / 2,
                    w = ctx.measureText(data[i].value).width,
                    b = Math.PI / 2 < a && a < Math.PI * 3 / 2;
                var c  = 0 < a && a < Math.PI;
                if(b){
                    ctx.textAlign = 'right';
                }
                else{
                    ctx.textAlign = 'left';
                }
                if(c){
                    ctx.translate(Math.cos(a) * outRadius +1 , Math.sin(a) * outRadius+1);

                }
                else{
                    ctx.translate(Math.cos(a) * outRadiustop, Math.sin(a) * outRadiustop);      
                }

                ctx.fillStyle = config.scaleFontColor;
                //If the segment angle less than 0.2, then the lables will overlap, so hiding it.
                if(segmentAngle > 0.2){
                    ctx.fillText(data[i].value,0,0);

                }
                ctx.restore();
     }

     ......
     ...... 

Ahora los valores se mostrarán al lado de cada sección y no se girarán.

 3
Author: Sareesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-10 11:03:16