techvigil-logo

Recently I was developing a small app to see the trend line of a process completion using Google chart tools. I was trying to put hour of the day in vertical or y-axis and date in horizontal or x-axis. I couldn't figure out any standard way to achieve this objective. So I did some kind of workaround.

On the x-axis I kept the date in standard format and used decimal value of hour in y-axis to render the graph. The value just helped to pull the curves but is not a good representation of data for end users. To make this more user readable, I added two things-

  1. Used custom tooltip to give more information on that point. (Lines 6 to 9 in the JavaScript code below)
  2. Added custom ticks in y-axis to represent hour of day instead of decimal value (Line 24)

This is sample PHP code to feed the graph data.

<?php
//this PHP code is used to generate JavaScript data - Lines 6 to 9 in the JavaScript code
//$ctime -> this variable is having process completion time in seconds
echo '[new Date(',date("Y",$ctime),',',(date("n",$ctime)-1),',',date("d",$ctime),'), ',date("G.i",$ctime),','<div style="padding:10px;"><p>Process Completed at ',date("H:i A",$ctime),'</p></div>']';
?>

JavaScript Code

google.charts.load('current', {'packages':['corechart']}); 
google.charts.setOnLoadCallback(drawChart); 
function drawChart() { 
	var data = google.visualization.arrayToDataTable([ 
		['Day', 'Process',{type: 'string', role: 'tooltip', 'p': {'html': true}}],
		[new Date(2017,2,10), 8.18,'<div style="padding:10px;"><p>Process Completed at 8:18 AM</p></div>'],
		[new Date(2017,2,09), 10.12,'<div style="padding:10px;"><p>Process Completed at 10:12 AM</p></div>'],
		[new Date(2017,2,08), 8.15,'<div style="padding:10px;"><p>Process Completed at 8:15 AM</p></div>'],
		[new Date(2017,2,07), 9.36,'<div style="padding:10px;"><p>Process Completed at 9:36</p></div>']
	]); 
		
	var options = { 
		title: 'Process Completion Trend - Last 4 Days', 
		curveType: 'function', 
		legend: { position: 'bottom' }, 
		animation:{ duration: 1000, easing: 'out', startup: true },
		tooltip: {isHtml: true}, 
		hAxis: {format:'E, d-MMM'}, 
		vAxis: {
			title: 'Time of day (GMT)',
			viewWindowMode:'maximized',
            //ticks is used to show custom text instead of actual integrar value
            //for example int value of 8 would be shown as 8:00 AM
			ticks: [
            	{v: 8, f: '8:00 AM'},
                {v: 9, f: '9:00 AM'},
                {v: 10, f: '10:00 AM'},
                {v: 11, f: '11:00 AM'}
             ]
		} 
	}; 
		
	var chart = new google.visualization.LineChart(document.getElementById('chart_div')); 
	chart.draw(data, options); 
}

419-google-chart-ticks.png

Try on JSFiddle

Post tagged in: CodesGoogle