Place a new array in the middle or center of the bar in Highcharts

Hi I’m using Highcharts and I’m trying to put in the middle of each bar, a value of a third array instead of the value of a second array but apparently not meeting documentation if possible.

It looks like this:

The idea is that, you see the corresponding value in the array $montos in the middle of each bar.

Code:


<?php

error_reporting(1);

include_once("conexion.php");
include_once("funciones.php");

$consulta = "";

if ($year == "") {
    $consulta = mysql_query("select id_deudor,month(fecha_pago_deudor) from deudores");
} else {
    $consulta = mysql_query("select id_deudor,month(fecha_pago_deudor) from deudores where year(fecha_pago_deudor)='" . $year . "'");
}

$monto_total = "0";

if ($year == "") {
    $monto_total = totalDeudores();
} else {
    $monto_total = totalDeudorPorYear($year);
}

if (!is_numeric($monto_total)) {
    $monto_total = "0";
}

$montos = array(
    "300",
    "400",
    "600",
    "800",
    "900",
    "200",
    "300",
    "100",
    "400",
    "600",
    "800",
    "900"
);

$cantidad = mysql_num_rows($consulta);

$ids = array();

$Enero      = 0;
$Febrero    = 0;
$Marzo      = 0;
$Abril      = 0;
$Mayo       = 0;
$Junio      = 0;
$Julio      = 0;
$Agosto     = 0;
$Septiembre = 0;
$Octubre    = 0;
$Noviembre  = 0;
$Diciembre  = 0;

while ($resultado = mysql_fetch_array($consulta)) {
    
    $id_cliente = $resultado[0];
    $mes_pago   = $resultado[1];
    
    if (!in_array($id_cliente, $ids)) {
        array_push($ids, $id_cliente);
        if ($mes_pago == 1) {
            $Enero++;
        }
        if ($mes_pago == 2) {
            $Febrero++;
        }
        if ($mes_pago == 3) {
            $Marzo++;
        }
        if ($mes_pago == 4) {
            $Abril++;
        }
        if ($mes_pago == 5) {
            $Mayo++;
        }
        if ($mes_pago == 6) {
            $Junio++;
        }
        if ($mes_pago == 7) {
            $Julio++;
        }
        if ($mes_pago == 8) {
            $Agosto++;
        }
        if ($mes_pago == 9) {
            $Septiembre++;
        }
        if ($mes_pago == 10) {
            $Octubre++;
        }
        if ($mes_pago == 11) {
            $Noviembre++;
        }
        if ($mes_pago == 12) {
            $Diciembre++;
        }
    }
    
}

$textos = array(
    "Enero",
    "Febrero",
    "Marzo",
    "Abril",
    "Mayo",
    "Junio",
    "Julio",
    "Agosto",
    "Septiembre",
    "Octubre",
    "Noviembre",
    "Diciembre"
);
$datos  = array(
    $Enero,
    $Febrero,
    $Marzo,
    $Abril,
    $Mayo,
    $Junio,
    $Julio,
    $Agosto,
    $Septiembre,
    $Octubre,
    $Noviembre,
    $Diciembre
);

$series = array();

for($i=0;$i<=11;$i++) {
	$serie = array( 'name' => $textos[$i] , 'data' => $datos[$i]) ;
	//$serie = array( 'name' => $textos[$i] , 'data' => $datos[$i]) ;
	array_push( $series,$serie);
//echo $textos[$i]." : ".$datos[$i]."
";
}

//echo $textos;
//echo $datos;

//echo "fuck";

?> 

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Highcharts Example</title>

		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		<style type="text/css">
${demo.css}
		</style>
		<script type="text/javascript">
$(function () {
    $('#container').highcharts({
        chart: {
            type: 'bar'
        },
        title: {
            text: 'Deudores'
        },
        subtitle: {
            text: 'Bla Bla'
        },
        xAxis: {
            categories: <?php echo json_encode($textos) ?>,
            title: {
                text: null
            }
        },
		
        yAxis: {
            min: 0,
            title: {
                text: 'Cantidad de deudores',
                align: 'high'
            },
            labels: {
                overflow: 'justify'
            }
        },
        tooltip: {
            useHTML: true,
            headerFormat: '<table>',
            //pointFormat: '<tr><th colspan="2"><h3>{point.montos}</h3></th></tr>';
            footerFormat: '</table>',
            followPointer: true
        },
		plotOptions: {
        series: {
            dataLabels:{
                enabled:true,
				format: '{point.montos}',
                formatter:function(){
                    if(this.y > 0)
                        return this.y;
                }
            }
        }
  		},
        legend: {
            //layout: 'vertical',
            //align: 'right',
            //verticalAlign: 'top',
            //x: -40,
            //y: 80,
            //floating: true,
            //borderWidth: 1,
            //backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
            //shadow: true
        },
        credits: {
            enabled: false
        },
        series: [{
            name: ['Cantidad de clientes'],
            data: <?php echo json_encode( $datos) ?>,
			montos : <?php echo json_encode($montos) ?>
        }]
    });
});
		</script>
	</head>
	<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; max-width: 800px; height: 400px; margin: 0 auto"></div>

	</body>
</html>

I’m trying to do this in two ways but I get no good

        tooltip: {
            useHTML: true,
            headerFormat: '<table>',
            //pointFormat: '<tr><th colspan="2"><h3>{point.montos}</h3></th></tr>';
            footerFormat: '</table>',
            followPointer: true
        },
		plotOptions: {
        series: {
            dataLabels:{
                enabled:true,
				format: '{point.montos}',
                formatter:function(){
                    if(this.y > 0)
                        return this.y;
                }
            }
        }

In the first thing I want to show the tooltip but when I use the line pointFormat not shown me the chart
In the second I want to show beside each bar as I had thought but still does not work and nothing is displayed

Can somebody help me ?

Hi, I am still unsure I understand what you are trying to do. So you have a bar chart with months and each month has certain value, which is graphed. But Im not sure I understand what you want to do next.

@JimmyBrain: I don’t understand it either :? Maybe you could draw/mark up an example?

An example :

It’s $600 because it is the position of the corresponding month this clear in the array $montos.

I had also tried to put it in the tooltip, but when I uncommented the line pointFormat shows me all the blank page.

I do not think you can use 'format: ‘{point.montos}’ as a data formatter - the ‘montos’ is not part of the Highcharts API. Have a look at the Highcharts ‘Labels and string formatting’ page to get a better idea of which parameters can be used for formatting.

I have been moving away from the (outdated) JpGraph - I have been converting many of my old scripts to the (more modern and well supported) Highcharts - well worth the API ‘learning curve’…

Ok now I understand, I will look at it in the evening today and let you know

I would like to do that too, and I’ve been looking for an example of using a delimited datafile and a timestamp based x axis :frowning:

Niko, using the old script to produce the JpGraph, I still use the delimited data but convert it to the JSON format using the PHP json_encode() function.

Without going into the details of how the default values for the Highcharts are setup, here is an example of the code I use to produce a one hour chart using the temperature data found in the ‘clientrawhour.txt’ data file:


$process_hour = get_time( 'clientrawhour.txt' );
// ------------------------------------------------------------------------
$datax = array( );
$datay = array( );
$HCtime = array( );
$HCtemp = array( );
// ------------------------------------------------------------------------
// creates an array of times for the x-axis
$ii = 0;
while ( $ii < 60 ) {
  if ( ( $ii == 0 ) || ( $ii == 10 ) || ( $ii == 20 ) || ( $ii == 30 ) || ( $ii == 40 ) || ( $ii == 50 ) || ( $ii == 59 )) {
    if ( $ii == 0 ) {
      $iii = '00';
    }
    else {
      $iii = $ii;
    }
    $datax[$ii] = $process_hour . ':' . $iii;
  }
  else {
    $datax[$ii] = ' ';
  }
  $ii = $ii + 1;
}
$HCtime = json_encode( $datax );
// for testing purposes
//echo '
count( $datax ) == '.count( $datax );
//echo '
$HCtime == '.$HCtime;
// ------------------------------------------------------------------------
// create an array of the values needed depending of the day of the week for the y-axis
$ii = 0;
$jj = 181;
while ( $ii < 60 ) {
  $datay[$ii] = floatval( strip_uom( $clientrawhour[$jj] ));
  $ii = $ii + 1;
  $jj = $jj + 1;
}
$HCtemp = json_encode( $datay );
// for testing purposes
//echo '
count( $datay ) == '.count( $datay );
//echo '
$HCtemp == '.$HCtemp;

The data contained in ‘$HCtime’ is used for the ‘xAxis’ whereas the data contained in ‘$HCtemp’ is used for the first ‘series’ (in the ‘yAxis’).

What I have done (after many hours of debugging) was to eventually create a default basic Highchart script into which I could import (almost) any kind of data.

@ R_o_B: Thanks for that, but unless I misunderstand it you are essentially making an array of labels for the x-axis. What I’m always doing in jpgraph, and would like to do in highcharts, is start with a file that has date/time stamped data e.g. “2015-12-23 23:58:04|47.14|20.07|0|43.92|6|170|338|507|680|853” and using strtotime to convert to a Unix timestamp, after which I can use the date formatting functions to set up my x-axis.

I think you try to do it more difficult than it is needed. Just do an array with timestamp and the data, convert it to json and give that to Highcharts. Then using the datetime x-axis setting + the formatting of the labels/tooltips and your are done.

<?php $timestamp=time()*1000; $data=1; $arr[]=array($timestamp,$data); echo ' '; ?>

// Henkka

OK, thanks I’ll play with that.

I found an example in Google Charts : http://jsfiddle.net/asgallant/QjQNX/

Looks to be exactly what you want :smiley:

Niko, to use raw date time values in HighCharts, just take your “strtotime to convert to a Unix timestamp” and multiply by 1000 to get a JavaScript raw date/time value. Unix uses seconds, and JavaScript milliseconds. Then if the x-axis is set to a date-time type, they will display correctly (you can also modify the default formats for different ranges of dates/times).

Thanks Mark :slight_smile: I have my project for the week…

OK, will one of you bright young folks please take pity on an old guy who is missing the final little piece of the puzzle :oops:

I have a working Highcharts graph stolen from the examples:

<!DOCTYPE HTML>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<title>Highcharts Example</title>

		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		<style type="text/css">
${demo.css}
		</style>
		<script type="text/javascript">
$(function () {
    $('#container').highcharts({
        chart: {
            type: 'spline'
        },
        title: {
            text: 'Testing Testing'
        },
        
        xAxis: {
            type: 'datetime',
            dateTimeLabelFormats: { 
                month: '%e. %b',
                year: '%b'
            },
            title: {
                text: 'Time'
            }
        },
        yAxis: {
            title: {
                text: 'Garbage Data'
            },
            min: 0
        },
        tooltip: {
            headerFormat: '<b>{series.name}</b>
',
            pointFormat: '{point.x:%e. %b}: {point.y:.2f} m'
        },

        plotOptions: {
            spline: {
                marker: {
                    enabled: true
                }
            }
        },

        series: [{
            name: 'Recent Data',
            
            data: [
                [1451331101000, 1],
                [1451331161000, 0.68],
                [1451331221000, 0.25],
                [1451331281000, 0.4],
                [1451331341000, 0.28],
                [1451331401000, 2.8],
                [1451331461000, 0.47],
                [1451331521000, 0.79],
                [1451331581000, 0.72],
                [1451331641000, 1.42],
                [1451331701000, 3.12],
            ]
        },  ]
    });
});
		</script>
	</head>
	<body>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

	</body>
</html>

And I have my php script which will generate a small correctly formatted timestamped array:

<?php

$row = 0;
if (($handlex = fopen("./skylog.txt", "r")) !== FALSE) {
    while (($rdata = fgetcsv($handlex, 1000, "|")) !== FALSE) {
        $num = count($rdata);

$dataone[$row][0] = strtotime($rdata[0])*1000;        
$dataone[$row][1] = $rdata[1];        

//        }
$row++;
    }
    fclose($handlex);
}
$datatwo = array_slice($dataone,-60);
//lets see what it looks like
echo json_encode($datatwo);
?>

I’ve tried a bunch of stuff but what I’m missing is how to get the array of data into data[] :frowning:

Niko, if you want to do it ‘inline’ on a PHP page then try…


        series: [{
            name: 'Recent Data',
            
            data: <?php include 'dataone.php'; ?>
        }]

Or, if you want to add the data using a client-side AJAX call…
First, keep a reference to the chart…


chart = $('#container').highcharts({
....

Then after the empty chart is drawn make your ajax call…


$.ajax({
	url: 'dataone.php',
	datatype: 'json',
	cache: false,
	success: function (resp) {
		chart.series[0].setData(resp);
	}
});


I’ve tried the first (php include)option, and some variations before and it just doesn’t want to work :?

Update: Stand by, I just noticed something…

I think I ID’d the problem. The output of http://realweatherstation.com/Hchart/examples/spline-irregular-time/dataone.php has quotes around the data:

[[1451335094000,"51.93"],[1451335140000,"51.93"],[1451335200000,"52.03"]]

But if I quote the data in the highchart code it doesn’t work. If I track that down it should be good.

Thanks Mark :smiley:

Do you have a test page up with the graph? I see you have fixed the JSON data (I normally use a (cast) to change text to numeric for PHP json data).