Google charts into JQuery Tab draw issue - javascript

I am currently trying to move Google charts in which the data is being pulled from the server-side via socket.io and drawing them into JQuery UI Tabs.
The issue am having is that the first report that gets drawn in works fine and looks fine.
The 2nd looks quite wrong, I think its something to do with how am drawing the tables maybe but am unable to find a solution, this issue does not happen when am simply drawing it into divs outside the JQuery UI tabs.
This is the current code I have right now:
jQuery(function ($) {
var socket = io.connect();
var result = [];
google.charts.load('current', {
packages : ['bar']
});
$(function() {
$( "#tabs" ).tabs();
});
socket.on("SQLdipo", function (valueArr) {
google.charts.setOnLoadCallback(drawMaterial);
var data = valueArr;
function drawMaterial() {
var result = [['Call Disposition', 'Answered', 'No Answer', 'Busy','Failed']].concat(valueArr);
var options = {
height: 350,
chart: {
title: 'Agent Call Dispositions',
subtitle: 'Agent call states',
}
};
var chartdata = new google.visualization.arrayToDataTable(result);
var chart1 = new google.charts.Bar(document.getElementById('chartDipo'));
chart1.draw(chartdata, options);
}
});
socket.on("SQLmins", function (valueArr) {
google.charts.setOnLoadCallback(drawChart);
var data = valueArr;
function drawChart() {
var result = [['Total Mins', 'Active','Inactive']].concat(valueArr);
var options = {
height: 350,
chart: {
title: 'Agent Activity in seconds',
subtitle: 'Agent Duration Activity',
}
};
var chartdata = new google.visualization.arrayToDataTable(result);
var chart2 = new google.charts.Bar(document.getElementById('chartMins'));
chart2.draw(chartdata, options);
}
});
});
I have made a configured a JS fiddle to emulate the issue am having HERE

the problem is the chart is hidden when it is initially drawn.
you could set specific size options or...
wait until the tab is activated, before drawing the chart for the first time, as in this example...
$(document).ready(function() {
$("#tabs").tabs({
activate: function(event, ui){
switch (ui.newTab.index()) {
case 0:
drawMaterial();
break;
case 1:
drawChart();
break;
}
}
});
google.charts.load('current', {
callback: drawMaterial,
packages: ['bar']
});
function drawMaterial() {
var data = google.visualization.arrayToDataTable([
['Call Disposition', 'Answered', 'No Answer', 'Busy', 'Failed'],
['1000', 4, 0, 2, 0],
['1001', 4, 2, 0, 0],
['1002', 6, 0, 0, 0]
]);
var options = {
height: 350,
chart: {
title: 'Agent Call Dispositions',
subtitle: 'Agent call states',
}
};
var chart1 = new google.charts.Bar(document.getElementById('chartDipo'));
chart1.draw(data, options);
}
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Call Disposition', 'Answered', 'No Answer', 'Busy', 'Failed'],
['1000', 4, 0, 2, 0],
['1001', 4, 2, 0, 0],
['1002', 6, 0, 0, 0]
]);
var options = {
height: 350,
chart: {
title: 'Agent Call Dispositions',
subtitle: 'Agent call states',
}
};
var chart1 = new google.charts.Bar(document.getElementById('chartMins'));
chart1.draw(data, options);
}
});
<link rel="stylesheet" type="text/css" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div class="tab-div" id="tabs">
<ul>
<li>Call Disposition</li>
<li>Agent Activity</li>
</ul>
<div id="tabs-1">
<div class="report-style" id="chartDipo"></div>
</div>
<div id="tabs-2">
<div class="report-style" id="chartMins"></div>
</div>
</div>

I have modified it with my own code based of the suggestion you gave #Whitehat which works fine but it means I have to use globals which I believe is not recommended.
What are your thoughts on this or any suggested changes or improvements?
jQuery(function ($) {
//Global Varibles
var socket = io.connect();
var result = [];
google.charts.load('current', {
packages : ['bar']
});
$("#tabs").tabs({
activate: function(event, ui){
switch (ui.newTab.index()) {
case 0:
drawMaterial();
break;
case 1:
drawChart();
break;
}
}
});
socket.on("SQLdipo", function (valueArr) {
google.charts.setOnLoadCallback(drawMaterial);
data1 = valueArr;
});
socket.on("SQLmins", function (valueArr) {
google.charts.setOnLoadCallback(drawChart);
data2 = valueArr;
});
function drawMaterial() {
var result = [['Call Disposition', 'Answered', 'No Answer', 'Busy','Failed']].concat(data1);
var options = {
height: 350,
chart: {
title: 'Agent Call Dispositions',
subtitle: 'Agent call states',
}
};
var chartdata = new google.visualization.arrayToDataTable(result);
var chart1 = new google.charts.Bar(document.getElementById('chartDipo'));
chart1.draw(chartdata, options);
}
function drawChart() {
var result = [['Total Mins', 'Active','Inactive']].concat(data2);
var options = {
height: 350,
chart: {
title: 'Agent Activity in seconds',
subtitle: 'Agent Duration Activity',
}
};
var chartdata = new google.visualization.arrayToDataTable(result);
var chart2 = new google.charts.Bar(document.getElementById('chartMins'));
chart2.draw(chartdata, options);
}
});

Related

google chart change color of individual histogram data points

I have the following code (see codepen) that allows me to change the color of each individual histogram data point after the chart is drawn. It works as intended. However, the colors mess up after the user hovers over the data points. What's going on and how can I fix it?
google.charts.load('current', {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var rawData = [
['Dinosaur', 'Length', 'color'],
['Acrocanthosaurus (top-spined lizard)', 12.2, 'red'],
['Albertosaurus (Alberta lizard)', 9.1, 'green'],
['Allosaurus (other lizard)', 12.2, 'green'],
];
// sort data by 'Length'
var data = google.visualization.arrayToDataTable(rawData);
data.sort([{column: 1}]);
var options = {
title: 'Lengths of dinosaurs, in meters',
legend: { position: 'none' },
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.Histogram(container);
google.visualization.events.addListener(chart, 'ready', function () {
var observer = new MutationObserver(function () {
var index = 0;
var item = 1;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function (rect) {
if (rect.getAttribute('fill') === '#3366cc') {
rect.setAttribute('fill', rawData[item][2]);
item++
}
index++;
});
});
observer.observe(container, {
childList: true,
subtree: true
});
});
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
in the observer, need to check for all colors...
switch (rect.getAttribute('fill')) {
case '#3366cc':
case 'red':
case 'green':
rect.setAttribute('fill', rawData[item][2]);
item++
break;
}
see following working snippet...
google.charts.load('current', {
packages:['corechart']
}).then(function drawChart() {
var rawData = [
['Dinosaur', 'Length', 'color'],
['Acrocanthosaurus (top-spined lizard)', 12.2, 'red'],
['Albertosaurus (Alberta lizard)', 9.1, 'green'],
['Allosaurus (other lizard)', 12.2, 'green'],
];
// sort data by 'Length'
var data = google.visualization.arrayToDataTable(rawData);
data.sort([{column: 1}]);
var options = {
title: 'Lengths of dinosaurs, in meters',
legend: { position: 'none' },
};
var container = document.getElementById('chart_div');
var chart = new google.visualization.Histogram(container);
google.visualization.events.addListener(chart, 'ready', function () {
var observer = new MutationObserver(function () {
var index = 0;
var item = 1;
Array.prototype.forEach.call(container.getElementsByTagName('rect'), function (rect) {
switch (rect.getAttribute('fill')) {
case '#3366cc':
case 'red':
case 'green':
rect.setAttribute('fill', rawData[item][2]);
item++
break;
}
index++;
});
});
observer.observe(container, {
childList: true,
subtree: true
});
});
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google chart only loads on refresh of page

Am a beginner using google charts/js. My google chart below loads fine, however there are times when the chart area loads blank html, and when I refresh the page it displays correctly.
I'm not sure why this is. It seems to do this on all browsers. This seems to indicate it could be with Mozilla, but the problem persists...
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() {
<?php
$imei = $bboxx_imei;
$result = shell_exec('Daily_Data_Retriever_ishackweb.py ' . $imei.' '. $end.' '.$start); #imei=sys.arg[1] end=sys.arg[2] start=sys.arg[3]
?>
var jsonData = <?php echo $result; ?> //{"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {0: {viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
$(window).resize(function(){
drawChart()
});
});
</script>
when using a function inline / anonymously, although you can provide a name,
you will not be able to call that same function again, by it's name
google.charts.load('current', {
packages: ['corechart']
}).then(function drawChart() { // <-- cannot call this again, no name needed
...
instead, declare the function separately, then pass a reference where needed,
using the name of the function
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
...
}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(drawChart);
$(window).resize(drawChart);
function drawChart() {
var jsonData = {"Charge Current, (A)":{"2017-11-16T00:00:00.000Z":0.001373312,"2017-11-16T00:01:00.000Z":0.001373312,"2017-11-16T00:02:00.000Z":0.001373312,"2017-11-16T00:03:00.000Z":0.001373312,"2017-11-16T00:04:00.000Z":0.001373312},"Battery Voltage, (V)":{"2017-11-16T00:00:00.000Z":12.9267109178,"2017-11-16T00:01:00.000Z":12.9267109178,"2017-11-16T00:02:00.000Z":12.9267109178,"2017-11-16T00:03:00.000Z":12.9267109178,"2017-11-16T00:04:00.000Z":12.9267109178}};
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
chartCols.push(column);
});
// build list of date
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
Object.keys(jsonData[column]).forEach(function (dateValue) {
if (dateValues.indexOf(dateValue) === -1) {
dateValues.push(dateValue);
}
});
});
// build chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
var row = [new Date(dateValue)];
Object.keys(jsonData).forEach(function (column) {
row.push(jsonData[column][dateValue] || null);
});
chartData.push(row);
});
var data = google.visualization.arrayToDataTable(chartData);
var options = {
chartArea: {width:'90%', height:'85%'},
//title: 'Battery Voltage and Panel Charge',
curveType: 'function',
legend: { position: 'bottom' },
vAxes: {
0: {
viewWindowMode:'explicit',
viewWindow:{
max:16,
min:11
},
gridlines: {color: 'transparent'},
},
1: {
viewWindowMode:'explicit',
viewWindow:{
max:5,
min:0
},
},
},
series: {
0: {targetAxisIndex:1},
1: {targetAxisIndex:0},
},
};
var chart = new google.visualization.LineChart(document.getElementById('line_chart'));
chart.draw(data, options);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="line_chart"></div>

1 Event Handler for 2 Google Charts

So, I have two Google bar charts displayed on the same page.I tried creating one event handler for both of them and passing in the chart and data into the selectHandler. Can someone tell me what I'm doing wrong?
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data1 = google.visualization.arrayToDataTable([
['Condition', 'Frequency'],
['Dementia', 6081],
['Hypertension', 6055],
['Hypercholesterolemia', 6035],
]);
var data2 = google.visualization.arrayToDataTable([
['Medication', 'Frequency'],
['Naproxen', 7632],
['Plavix', 7486]
]);
var options1 = {
title: 'Medical Conditions',
};
var options2 = {
title: 'Medications',
};
var conditionbarchart = new google.charts.Bar(
document.getElementById('conditions_chart'));
conditionbarchart.draw(data1, options1);
var medchart = new google.visualization.ColumnChart(
document.getElementById('medications_chart'));
medchart.draw(data2, options2);
google.visualization.events.addListener(conditionbarchart, 'select', selectHandler(conditionbarchart, data1));
google.visualization.events.addListener(medchart, 'select', selectHandler());
}
function selectHandler(mychart, mydata){
var selectedItem = mychart.getSelection()[0];
if(selectedItem){
var selection = mydata.getValue(selectedItem.row, 0);
alert('The user selected' + selection);
}
}
Here's the complete solution to answer my question:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Condition');
data.addColumn('number', 'Frequency');
data.addRows([
['Dementia', 3],
['Hypertension', 1],
['Hypercholesterolemia', 1],
['Coronary artery disease', 1],
['Heaches', 2]
]);
// Create the data table.
var data2 = new google.visualization.DataTable();
data2.addColumn('string', 'Medication');
data2.addColumn('number', 'Frequency');
data2.addRows([
['Naproxen', 3],
['Plavix', 1],
['Lasix', 1],
['Insulin', 1],
['Neurontin', 2]
]);
// Set chart options
var options = {
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {
slantedText:true,
slantedTextAngle:90
},
height: 400,
backgroundColor: {fill: 'transparent'},
legend: {position: 'none'},
colors: ['#1b9e77']
};
// Set chart options
var options2 = {
bars: 'vertical', // Required for Material Bar Charts.
hAxis: {
slantedText:true,
slantedTextAngle:90
},
height: 400,
backgroundColor: {fill: 'transparent'},
legend: {position: 'none'},
colors: ['#1b9e77']
};
// Instantiate and draw our chart, passing in some options.
var conditionsbarchart = new google.visualization.ColumnChart(document.getElementById('conditions_chart'));
var medchart = new google.visualization.ColumnChart(document.getElementById('medications_chart'));
function selectHandler(mychart, mydata) {
var selectedItem = mychart.getSelection()[0];
if (selectedItem) {
var topping = mydata.getValue(selectedItem.row, 0);
alert('The user selected ' + topping);
}
}
google.visualization.events.addListener(conditionsbarchart, 'select', function(){
selectHandler(conditionsbarchart, data);
});
conditionsbarchart.draw(data, options);
google.visualization.events.addListener(medchart, 'select', function(){
selectHandler(medchart, data2);
});
medchart.draw(data2, options2);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="conditions_chart" style="width:400; height:300"></div>
<div id="medications_chart" style="width: 400; height: 300"></div>
</body>
</html>

Hover on google chart acting weird on firefox

When adding a hover event to google chart svg element the results are different between firefox and chrome (chrome is doing what I would expect).
What I would like to achieve is the ability for the user to hover on a chart and not care how close he is to the line - the hover should be smooth and easy to use.
Here is the relevant plunker: https://plnkr.co/edit/2IF2BnX0tS2wznAUr5bs?p=preview
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script>
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var dataTable = new google.visualization.DataTable({
cols: [
{ id: 'x', label: 'Num', type: 'number' },
{ id: 'y', label: 'Fn', type: 'number' }
]
});
for (var i = 0; i < 1000; i++) {
var xValue = { v: i };
var yValue = { v: i };
// add data row
dataTable.addRow([
xValue,
yValue
]);
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: dataTable,
options: {
hAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is also fine'
},
tooltip: {
trigger: "none"
},
vAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is OK'
}
}
});
// add hover line
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
var svgParent = container.getElementsByTagName('svg')[0];
var layout = chart.getChart().getChartLayoutInterface();
var lineHeight = layout.getBoundingBox('chartarea').height - 18;
var lineTop = layout.getBoundingBox('chartarea').top;
var hoverLine = container.getElementsByTagName('rect')[0].cloneNode(true);
hoverLine.setAttribute('y', lineTop);
hoverLine.setAttribute('height', lineHeight);
hoverLine.setAttribute('width', '1');
hoverLine.setAttribute('stroke', 'none');
hoverLine.setAttribute('stroke-width', '0');
hoverLine.setAttribute('fill', '#cccccc');
hoverLine.setAttribute('x', 0);
svgParent.appendChild(hoverLine);
svgParent.addEventListener("mousemove", function (e) {
hoverLine.setAttribute('x', e.offsetX);
});
});
chart.draw(container);
}
</script>
<div id="chart_div"></div>
Hover on the chart with chrome to see the expected behaiour.
Hover on the chart with firefox to see the issue.
Any idea how to solve this? is this a google chart bug? Am I adding an event listener to the wrong element?
It seems that the children tags in your svg are capturing the mousemove events (which makes since due to event propogation).
Simply add a pointer-events:none to those children elements (I recommended to use an id for that svg element)
svg *{
pointer-events: none;
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<script>
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var dataTable = new google.visualization.DataTable({
cols: [
{id: 'x', label: 'Num', type: 'number'},
{id: 'y', label: 'Fn', type: 'number'}
]
});
for (var i = 0; i < 1000; i++) {
var xValue = { v: i };
var yValue = { v: i };
// add data row
dataTable.addRow([
xValue,
yValue
]);
}
var container = document.getElementById('chart_div');
var chart = new google.visualization.ChartWrapper({
chartType: 'LineChart',
dataTable: dataTable,
options: {
hAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is also fine'
},
tooltip: {
trigger: "none"
},
vAxis: {
gridlines: {
color: 'transparent'
},
title: 'Hover here is OK'
}
}
});
// add hover line
google.visualization.events.addOneTimeListener(chart, 'ready', function () {
var svgParent = container.getElementsByTagName('svg')[0];
var layout = chart.getChart().getChartLayoutInterface();
var lineHeight = layout.getBoundingBox('chartarea').height - 18;
var lineTop = layout.getBoundingBox('chartarea').top;
var hoverLine = container.getElementsByTagName('rect')[0].cloneNode(true);
hoverLine.setAttribute('y', lineTop);
hoverLine.setAttribute('height', lineHeight);
hoverLine.setAttribute('width', '1');
hoverLine.setAttribute('stroke', 'none');
hoverLine.setAttribute('stroke-width', '0');
hoverLine.setAttribute('fill', '#cccccc');
hoverLine.setAttribute('x', 0);
svgParent.appendChild(hoverLine);
svgParent.addEventListener("mousemove", function(e) {
hoverLine.setAttribute('x', e.offsetX);
});
});
chart.draw(container);
}
</script>
<div id="chart_div"></div>
</body>
</html>

change tooltip name(current & previous) in google diff chart

I want to create a google diff chart for a survey. that will show the total number of user and survey given users.
My javascript code is:-
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var overallData = [];
var givenData = [];
overallData.push(['Department', 'Total Users']);
givenData.push(['Department', 'Given feedback']);
for (var i in data) {
overallData.push([data[i].department_name, data[i].emp_count]);
givenData.push([data[i].department_name, data[i].upward_done]);
}
var oldData = google.visualization.arrayToDataTable(overallData);
var newData = google.visualization.arrayToDataTable(givenData);
var colChartDiff = new google.visualization.ColumnChart(document.getElementById('feedback_dept_chart'));
var options = {
fontName: 'Calibri',
legend: 'none',
height: 200,
width: 960,
vAxis: {title: 'No of employee'},
tooltip: {isHtml: false}
};
var diffData = colChartDiff.computeDiff(oldData, newData);
colChartDiff.draw(diffData, options);
And data is :-
[{"department_name":"Design","emp_count":1,"upward_done":1},
{"department_name":"Management","emp_count":1,"upward_done":0},
{"department_name":"Technology","emp_count":3,"upward_done":2}]
The problem with diff chart is it is showing tooltip named "current" and "previous". And I want to change it by "total users" and "survey given users".
Any help will be appreciated.
Thanks
Add below code for tooltip into options
diff: {
oldData: { opacity: 1, color: 'yellow',
tooltip:{
prefix:'Label 1'
}
},
newData: { opacity: 1, widthFactor: 1,
tooltip:{
prefix:'Label 2'
}
}
}

Categories