Google Pie Charts is not displayed when data has more than one Row

Asked

Viewed 882 times

2

I am trying to display a Piechart, however, if the search in the database returns only one line, the chart is displayed. If it returns more than one line, the graph does not appear.

function generating graph data:

public function grpAplicacaoRecursos() {
// Estrutura basica do grafico
    $grafico = array(
        'dados' => array(
            'cols' => array(
                array('type' => 'string', 'label' => 'Descricao'),
                array('type' => 'number', 'label' => 'Valor')
            ),
            'rows' => array()
        ),
        'config' => array(
            'title' => 'Para onde vai meu dinheiro',
            'width' => 400,
            'height' => 250
        )
    );

    $dataAtual = new DateTime('now');
    $inicioUltimaSemana = date('Y-m-d', strtotime($dataAtual->format('Y-m-d').' -365 days'));


    $dados = $this->registry->conn->fetchAll('SELECT c.descricao descricao, sum(m.valor) valor '.
            'FROM movimento_conta m left join conta c on m.conta_id = c.conta_id where m.data '.
            'between ? and ? group by descricao ', array($inicioUltimaSemana, $dataAtual->format('Y-m-d')));

    foreach ($dados as $row) {
        $grafico['dados']['rows'][] = array('c' => array(
                array('v' => $row['descricao']),
                array('v' => $row['valor'])
        ));
    }
    // Enviar dados na forma de JSON
    header( 'Cache-Control: no-cache' );
    header('Content-Type: application/json; charset=UTF-8');
    echo json_encode($grafico);
}

function return:

{  
"dados":{  
  "cols":[  
     {  
        "type":"string",
        "label":"Descricao"
     },
     {  
        "type":"number",
        "label":"Valor"
     }
  ],
  "rows":[  
     {  
        "c":[  
           {  
              "v":"teste1"
           },
           {  
              "v":"554.890"
           }
        ]
     },
     {  
        "c":[  
           {  
              "v":"teste2"
           },
           {  
              "v":"2556.000"
           }
        ]
     }
  ]
},
"config":{  
  "title":"Para onde vai meu dinheiro",
  "width":400,
  "height":250
}
}

script on the page that displays the chart:

<script type="text/javascript">
google.load('visualization', '1.0', {'packages': ['corechart']});
google.setOnLoadCallback(function() {
    var json_text = $.ajax({url: "/index/grpAplicacaoRecursos", dataType: "json", async: false}).responseText;
    var json = eval("(" + json_text + ")");
    var dados = new google.visualization.DataTable(json.dados);

    var chart = new google.visualization.PieChart(document.getElementById('area_grafico2'));
    chart.draw(dados, json.config);
});


</script>

Can anyone tell me what I’m doing wrong ?

  • Did you find a solution? Poste as an answer to help other people.

1 answer

1

Actually you expected to see something like this:

inserir a descrição da imagem aqui

If it is, it’s pretty simple to solve even though it’s not so obvious: Its decimal values are not decimal, they’re numerical strings.

Most likely the fault is how Google Charts interprets the information of the informed JSON.

If I had to guess I’d say that because you’re defining a type as number but be passing a string, when this value is converted to the rule number you set, it should result in some unexpected value.

Remove quotes from values by forcing the variable to float cast and the graph should appear (must because I modified the JSON manually):

foreach ($dados as $row) {
    $grafico['dados']['rows'][] = array('c' => array(
        array('v' => $row['descricao']),
        array('v' => (float) $row['valor'])
    ));
}

Discarding the zeros to the right of the decimal place also makes the graph appear, even without changing the type of the variable, but the results I got were different.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.