<?php 
$sql = 
"SELECT idrp_provincia, rp_provincia.CodigoProvincia, NombreProvincia, COUNT(*) municipios
FROM rp_provincia left JOIN  rp_municipio on ( rp_provincia.CodigoProvincia = rp_municipio.CodigoProvincia )
Group by 1,2,3
Order By 4 desc
limit 10";
$rs = DB::Query($sql);
$dataValue = array();
$dataLabel = array();
while ($data = $rs->fetchAssoc()) {
    $dataLabel[]= $data['NombreProvincia'];
    $dataValue[]= $data['municipios'];
}

use mitoteam\jpgraph\MtJpGraph;
require __DIR__."/../jpgraph_10.2.2/autoload.php";

// load library and modules
MtJpGraph::load(['bar']); 

$datay=$dataValue;

// Create the graph. 

$graph = new Graph(800,600,'auto');
$graph->SetScale("textlin");
$graph->img->SetMargin(60,30,20,100);
$graph->yaxis->SetTitleMargin(45);
$graph->yaxis->scale->SetGrace(30);
$graph->xaxis->SetTickLabels($dataLabel);
$graph->xaxis->SetLabelAngle(20);
$graph->SetShadow();


// Special 
$graph->graph_theme = null;
$graph->SetFrame(false);

// Create a bar pot
$bplot = new BarPlot($datay);

$bplot->SetColor("white");

// Use a shadow on the bar graphs (just use the default settings)
//  $bplot->SetShadow();
$bplot->value->SetFormat(" %2.0f",70);
$bplot->value->SetFont(FF_FONT1,FS_NORMAL,9);
$bplot->value->SetColor("black");
$bplot->value->Show();

$graph->Add($bplot);

// $graph->title->Set("Image maps barex1");
// $graph->xaxis->title->Set("Provincias");
$graph->yaxis->title->Set("Numero de Municipios");

$graph->title->SetFont(FF_FONT1,FS_BOLD);
$graph->yaxis->title->SetFont(FF_FONT1,FS_NORMAL);
$graph->xaxis->title->SetFont(FF_FONT1,FS_NORMAL);

// Send back the HTML page which will call this script again
// to retrieve the image.
$file = tempnam(sys_get_temp_dir(), 'png');
$filePNG = str_replace(".", "_",$file).'.png';
unlink($file); // Delete file
$graph->Stroke($filePNG);

// $graph->StrokeCSIM();
?>
