Why doesn't my Google chart work on Safari? - javascript

I am trying to draw a chart on screen using Google charts. It works on every browser except for Safari. The following is the code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the bar chart package.
google.charts.load("current", {"packages":["corechart", "line"]});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "/get-data-for-chart",
data: {"objectId": 807},
dataType: "json"
}).then(function(response) {
// Create our data table out of JSON data loaded from server.
rawData = response;
if (rawData.rows != null) rawData.rows = rawData.rows.map(row => ({ c: [{ v: new Date(row.c[0].v) }, row.c[1]] }));
var data = new google.visualization.DataTable(rawData);
// Instantiate and draw our chart, passing in some options.
var options = {
chart: {
title: "Title of the chart"
},
width: 900,
height: 500,
hAxis: {
title: "Time Axis",
format: "MM-dd",
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: "none"},
minValue: 0,
format: "currency"
}
};
var date_formatter = new google.visualization.DateFormat({
pattern: "MMM dd, yyyy HH:mm"
});
date_formatter.format(data, 0);
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, options);
});
}
</script>
<!--Div that will hold the chart-->
<div id="chart_div"></div>
What actually happens on Safari is that the area for the chart loads, but with incorrect labels I guess. And the actual chart does not load at all. Moreover, there are no errors shown in the console, so I can't debug this in a usual way. As mentioned earlier, this works with all other browsers. Also for the record, the Safari is running on MacOS Mojave. Any help is greatly appreciated! Thanks.

Related

Chart js - Chart doesn't show when x axis has type 'time'

I'm working on Char.js version 3.9.1 and I have a chart which display data (y value) along the time (x value). Everything seems to be working fine.
However, when I add 'type' property to x axis in order to make the x scale to have daily unit, the chart doesn't show anything. I have tried running code in jsfiddle and the console shows error "Uncaught Error: This method is not implemented: Check that a complete date adapter is provided." I tried searching the internet and still not find any solution.
Here is my code (I have to add comment over type: 'line' to make the chart to display).
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS7UJZNeml5ALk+8IKlU6jDgMabC3vkumRokgJA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id="mychart"></canvas>
Javascript
let data = [12, 14, 13, 18, 21, 22, 25];
let labels = ["2017-01-20", "2017-01-22", "2017-01-24", "2017-01-26", "2017-01-28", "2017-01-30", "2017-02-01"];
let options = {
scales: {
x: {
type: 'time', //this line make the chart disappear
time: {
unit: 'day'
}
},
y0: {
ticks: {
min: 0
}
},
},
};
let chartData = {
labels: labels,
datasets: [{
data: data,
label: 'Amount of Stuff',
backgroundColor: '#035e7b',
}]
};
let ctx = document.getElementById('mychart').getContext('2d');
new Chart(ctx, {
data: chartData,
type: 'line',
options: options,
});
From the docs:
Date Adapters
The time scale requires both a date library and a
corresponding adapter to be present. Please choose from the
available adapters.
So you can change your HTML like this:
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js" integrity="sha512-ElRFoEQdI5Ht6kZvyzXhYG9NqjtkmlkfYk0wr6wHxU9JEHakS7UJZNeml5ALk+8IKlU6jDgMabC3vkumRokgJA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.jsdelivr.net/npm/moment#^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment#^1"></script>
<canvas id="mychart"></canvas>
and then you'll be able to use type: "time" for x axis.

Google Charts not Working When Data Table is Global

I'm working on a small HTML application for my website that does some simulations and plots it to a graph (using Google Charts). All of the data will originate in the JavaScript code on the page (i.e. I'm not trying to pull in data from a database or anything like that). For this reason, I would like to have access to the data table from other functions so the data can be updated when a new simulation is run.
What I'm running into is that if I build a data table (and data view) inside of the drawChart() function, everything works fine. See this jsfiddle or the following code:
//Google charts stuff
google.charts.load('current', { 'packages': ['line', 'corechart'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var forceChartDiv = document.getElementById('force_chart_div');
var sim_data = new google.visualization.DataTable();
sim_data.addColumn('number', 'Elapsed Time (sec)');
sim_data.addColumn('number', "Total Force");
sim_data.addColumn('number', "M1 Force(Each)");
sim_data.addRows([
[0.0, -.5, 5.7],
[0.1, .4, 8.7],
[0.2, .5, 12]
]);
var forceDataView = new google.visualization.DataView(sim_data);
forceDataView.setColumns([0, 1, 2]);
var forceChartOptions = {
chart: {title: 'Simulation Results: Force'},
width: 900,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: { axis: 'Total' },
1: { axis: 'Individual' }
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Total: { label: 'Total Force (Newtons)'},
Individual: { label: 'Per-Motor Force (Newtons)'}
}
}
};
var forceChart = new google.charts.Line(forceChartDiv);
forceChart.draw(forceDataView, google.charts.Line.convertOptions(forceChartOptions));
}
But if I move the code for the creation of the data table and data view outside of the function scope, it doesn't work. See this jsfiddle or the following code:
var sim_data;
var forceDataView;
//Google charts stuff
google.charts.load('current', { 'packages': ['line', 'corechart'] });
sim_data = new google.visualization.DataTable();
sim_data.addColumn('number', 'Elapsed Time (sec)');
sim_data.addColumn('number', "Total Force");
sim_data.addColumn('number', "M1 Force(Each)");
sim_data.addRows([
[0.0, -0.5, 5.7],
[0.1, 0.4, 8.7],
[0.2, 0.5, 12]
]);
forceDataView = new google.visualization.DataView(sim_data);
forceDataView.setColumns([0, 1, 2]);
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var forceChartDiv = document.getElementById('force_chart_div');
var forceChartOptions = {
chart: {title: 'Simulation Results: Force'},
width: 900,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: { axis: 'Total' },
1: { axis: 'Individual' }
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Total: { label: 'Total Force (Newtons)'},
Individual: { label: 'Per-Motor Force (Newtons)'}
}
}
};
var forceChart = new google.charts.Line(forceChartDiv);
forceChart.draw(forceDataView, google.charts.Line.convertOptions(forceChartOptions));
}
Both of these examples use the following HTML:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="force_chart_div"></div>
I thought it might have something to do with the execution order of the callback function. But putting it in different spots in the code doesn't seem to change anything. In my full project, I went so far as to add a button that called the drawChart() function just to check, but that didn't help either.
Depending on where I put the callback function call, I'll get a red "Data Table is not Defined" alert showing up where the chart is supposed to be on the webpage. That pretty much tells me what I already suspected, but I don't know how to fix it. Any help would be appreciated. I'm a huge JS noob, by the way, so go easy on me.
your instinct was correct, you must wait on the callback to finish,
before using the google.visualization or google.charts namespaces.
it has to do more with timing, than placement of the code.
instead of using the callback statement, we can use the promise that the load statement returns.
as in the following snippet...
var sim_data;
var forceDataView;
//Google charts stuff
google.charts.load('current', {
packages: ['line', 'corechart']
}).then(function () {
sim_data = new google.visualization.DataTable();
sim_data.addColumn('number', 'Elapsed Time (sec)');
sim_data.addColumn('number', "Total Force");
sim_data.addColumn('number', "M1 Force(Each)");
sim_data.addRows([
[0.0, -0.5, 5.7],
[0.1, 0.4, 8.7],
[0.2, 0.5, 12]
]);
forceDataView = new google.visualization.DataView(sim_data);
forceDataView.setColumns([0, 1, 2]);
});
function drawChart() {
var forceChartDiv = document.getElementById('force_chart_div');
var forceChartOptions = {
chart: {title: 'Simulation Results: Force'},
width: 900,
height: 500,
series: {
// Gives each series an axis name that matches the Y-axis below.
0: { axis: 'Total' },
1: { axis: 'Individual' }
},
axes: {
// Adds labels to each axis; they don't have to match the axis names.
y: {
Total: { label: 'Total Force (Newtons)'},
Individual: { label: 'Per-Motor Force (Newtons)'}
}
}
};
var forceChart = new google.charts.Line(forceChartDiv);
forceChart.draw(forceDataView, google.charts.Line.convertOptions(forceChartOptions));
}

Google Bar chart Bar color not changing

I'm using google bar chart to represent set of issues into different categories like open, closed, in progress etc., I'm getting the count of different categories and storing it to a hashmap, and then I retrieve the data from hashmap and displaying it in the bar chart using the below code.
Edited below is the code that I'm using. I've included it in a jsp page
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawBarChart);
function drawBarChart() {
var data = google.visualization.arrayToDataTable([
['Status', 'No. of Issues', { role: 'style' }],
<%for(String SC:StatusCount.keySet()){
%>
['<%=SC.toString()%>',<%=StatusCount.get(SC.toString())%>, 'blue'],
<%
}
%>
<%for(String EC:EscCount.keySet()){
%>
['<%=EC.toString()%>',<%=EscCount.get(EC.toString())%>, 'red' ],
<%
}
%>
]);
var options = {
chart: {
title: 'Performance',
},
is3D: true,
titleTextStyle: {
fontName: 'Arial',
fontSize: 20
},
'width':550,
'height':400,
backgroundColor: 'transparent',
bars: 'vertical' // Required for Material Bar Charts.
};
var barchart = new google.charts.Bar(document.getElementById('barchart_material'));
barchart.draw(data, google.charts.Bar.convertOptions(options));
}
StatusCount is used for the status count and EscCount for the no of escalations. I wanted to change the color of the Escalations bar. But when I specify the color, it's not getting changed. Used the same thing that Google itself has given to change the color.
Kindly help. Thanks in advance
Column Roles, including 'style' are only supported by Classic charts...
Classic --> google.visualization.BarChart & ColumnChart --> packages: ['corechart']
Material --> google.charts.Bar --> packages: ['bar']
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Status', 'No. of Issues', { role: 'style' }],
['Closed',14, 'blue'],
['On Hold',8, 'blue'],
['In Progress',20, 'blue'],
['Open',24, 'blue'],
['Escalations',4, 'red'],
]);
var chart = new google.visualization.BarChart(
document.getElementById('chart_div')
);
chart.draw(data, {
theme: 'material'
});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Line chart from CSV

I am quite new to java-script and html stuff.. I am trying to make a basic line chart with Google chart using example.csv file but something is wrong. I dont see any chart. Nothing is being displayed. Please help. I came up with code after reading some similar codes
All i need is to start with this basic working code and develop into more advanced shape
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery.csv-0.71.js"></script>
<script type="text/javascript">
//google.load('visualization', '1', {packages: ['corechart', 'line']});
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(BasicLine);
function BasicLine() {
// grab the CSV
$.get("example.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
var data = new google.visualization.arrayToDataTable(arrayData);
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Temperature'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
My CSV File is as below
Hour, Temperature
1, 70
2, 65
3, 60
4, 65
5, 67
6, 69
There is an syntax-error(the console should have told you about this).
Fixed version:
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(BasicLine);
function BasicLine() {
$.get("example.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString,
{onParseValue: $.csv.hooks.castToScalar}),
data = new google.visualization.arrayToDataTable(arrayData),
options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Temperature'
},
backgroundColor: '#f1f8e9'
},
chart = new google.visualization
.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
'text');
}
</script>

Google column chart bug with the drawing in Web app

In my web app there is a google chart that uses dataTable(jsonObject) to draw the graphs and I have bugged data. Here is my code of calling the function :
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
function drawChart() {
var myJson= $.ajax({
url: "loadGraph.php",
dataType:"json",
async: false
}).responseText;
var visualization = new google.visualization.DataTable(myJson);
var options = {
title: "MyTitle",
titleTextStyle: { fontSize: 16, bold: true },
chartArea: { left: 32, right: 0,left: 52, width: 460, height: 180 },
legend: { position: 'top' }
}
var chart = new google.visualization.ColumnChart(document.getElementById('chartDiv'));
chart.draw(visualization , options);
}
google.setOnLoadCallback(drawVisualization);
</script>
My graph was correctly drawed, but recently a bugs occured. Please help
Check my post on this matter : Google column chart visualization from json object bug in MVC 4 C#
There is a bug on this type of displaying the charts. The good part is that the solution is pretty slick. Replace the values for the chart with this regex ->
myJson = myJson.replace(/"v":"(\d+)"/g, '"v":$1');
This will fix the visualization ;] Hope this helps

Categories