3

Galera estou usando uma plugin para Jquery chamado Chart JS.

Bom e bem simples trabalhar com o plugin, o problema e que eu informo valores no padrão americano (33.33) e eu preciso que o gráfico exiba eles no padrão PT-BR (R$33,33)

Alguém sabe como fazer isso?

Segue o modelo simples do gráfico:

var options = {
        scaleFontFamily: "'Verdana'",
        scaleFontSize: 13,
        animation: false,
        scaleFontColor: "#484848",
        responsive: true
    };

    var data = {
        labels: ["Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro"],
        datasets: [
            {
                label: "2016",
                fillColor: "rgba(0,145,255,0.2)",
                strokeColor: "rgba(0,145,255,1)",
                pointColor: "rgba(0,145,255,1)",
                pointStrokeColor: "#fff",
                pointHighlightFill: "#fff",
                pointHighlightStroke: "rgba(0,145,255,1)",
                data: [199.99, 2888.99, 123.12, 3457.12, 124, 16885.33, 3578.34, 57853.34, 4678.12, 8754, 24657.55, 2345.33]
            }

        ]
    };

    window.onload = function () {
        var ctx = document.getElementById("lineChart").getContext("2d");
        new Chart(ctx).Line(data, options);
        legend(document.getElementById("lineLegend"), data);
    };

    function legend(parent, data) {
        legend(parent, data, null);
    }

    function legend(parent, data, chart, legendTemplate) {

        legendTemplate = typeof legendTemplate !== 'undefined' ? legendTemplate : "<%= label %>";
        parent.className = 'legend';
        var datas = data.hasOwnProperty('datasets') ? data.datasets : data;

        while (parent.hasChildNodes()) {
            parent.removeChild(parent.lastChild);
        }

        var show = chart ? showTooltip : noop;
        datas.forEach(function (d, i) {

            // Span to div: legend appears to all element (color-sample and text-node)
            var title = document.createElement('div');
            title.className = 'title';
            parent.appendChild(title);

            var colorSample = document.createElement('div');
            colorSample.className = 'color-sample';
            colorSample.style.backgroundColor = d.hasOwnProperty('strokeColor') ? d.strokeColor : d.color;
            colorSample.style.borderColor = d.hasOwnProperty('fillColor') ? d.fillColor : d.color;
            title.appendChild(colorSample);
            legendNode = legendTemplate.replace("<%= value %>", d.value);
            legendNode = legendNode.replace("<%= label %>", d.label);
            var text = document.createTextNode(legendNode);
            text.className = 'text-node';
            title.appendChild(text);

            show(chart, title, i);
        });
    }

// Add events to legend that show tool tips on chart
    var Chart;
    function showTooltip(chart, elem, indexChartSegment) {
        var helpers = Chart.helpers;

        var segments = chart.segments;
        // Only chart with segments
        if (typeof segments !== 'undefined') {
            helpers.addEvent(elem, 'mouseover', function () {
                var segment = segments[indexChartSegment];
                segment.save();
                segment.fillColor = segment.highlightColor;
                chart.showTooltip([segment]);
                segment.restore();
            });

            helpers.addEvent(elem, 'mouseout', function () {
                chart.draw();
            });
        }
    }

    function noop() {
    }
  body {
                margin: 0;
                color:#484848;

                font-family: Verdana; 
                font-size: 13px;
            }


            .box-grafico1 {
                margin: 0px auto;
                width: 90%;
            }
            .box-grafico2 {
                width: 690px;
            }
            #fork {
                position: absolute;
                top: 0;
                right: 0;
                border: 0;
            }
            .legend {
                margin-top: 15px;
                width: 90%;
            }
            .legend .title {
                float: left;
                display: block;
                margin-bottom: 0.5em;
                line-height: 1.2em;
                padding: 0 0.3em;
            }
            .legend .color-sample {
                display: block;
                float: left;
                width: 1em;
                height: 1em;
                border: 2px solid;
                border-radius: 100px;
                margin-right: 0.5em;
            }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://www.alvoradatratores.com.br/Chart.min.js"></script>

    
<div class="box-grafico1">
            <canvas id="lineChart"></canvas>
            <div id="lineLegend"></div>
        </div>

2
  • Queres formatar o resultado no eixo do Y ou dentro do gráfico na informação que aparece?
    – Sergio
    19/04/2016 às 17:42
  • Os dois :) . Queria formatar todo o gráfico se possível. 19/04/2016 às 17:51

2 Respostas 2

3

Isso é possível através das opções do gráfico (existente mas pouco claro na documentação), usando tooltipTemplate e scaleLabel para mudar respectivamente o texto dentro do gráfico e o eixo do Y.

Na prática poderia ser feito assim:

var formatedString = '<%= "R$ " + value.toString().split(".").join(",") %>';

var options = {
    scaleFontFamily: "'Verdana'",
    scaleFontSize: 13,
    animation: false,
    scaleFontColor: "#484848",
    responsive: true,
    tooltipTemplate: formatedString,
    scaleLabel: formatedString
};

jsFiddle: http://jsfiddle.net/s8wzfku4/

Se quiseres podes também usar uma função para formatar a string. A função recebe um objeto como primeiro argumento e o valor está na propriedade .value. Por exemplo assim: http://jsfiddle.net/8xkk4gps/2/

1
  • Amigo, poderia me ajudar? a algum tempo atrás vc me ajudar com esta resposta, que vinha funcionando 100%. porem hoje me deparei com um problema, se eu colocar mais de 1 resultado no gráfico a formatação não funciona, poderia me ajudaR? segue o link do exemplo. jsfiddle.net/8xkk4gps/6 2/08/2016 às 11:13
0

Quando trabalhar com mais de um dataset, deve utilizar a opção multiTooltipTemplate em vez de tooltipTemplate.

Ex.

multiTooltipTemplate: function(data) {
    return formatar(data.value);
  }

Atualizei seu exemplo dessa forma e está funcionando.

http://jsfiddle.net/8xkk4gps/9/

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .