Uncaught Error: Invalid value in 0,0 - javascript

I'm having a really weird issue while trying to visualize this scatter plot using the google visualization API.
Basically, if I put the first data point as [0,0] everything will be fine, but if remove [0,0] as the first point, the chart won't produce. I checked the console and this is what it said:
"Uncaught SyntaxError: Unexpected token <
Uncaught Error: Invalid value in 0,0"
Why exactly does the first point need to be [0,0]?
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Camera','Avg Rating'],
[ {v:6000, f: 'Canon EOS-1Ds Mark III'}, 60],
[ {v:5000, f: 'Canon EOS-1Ds Mark II'}, 50],
[ {v:4000, f: 'Canon EOS-1D Mark IV'}, 40]
]);
var options = {
title: 'Breakdown of Camera Models by Price, Photo Rating and Brand',
hAxis: {title: 'Price (USD)', minValue: 0, maxValue: 7500},
vAxis: {title: 'Avg Rating (at peak)', minValue: 0, maxValue: 55},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 1000px; height: 1000px;"></div>
</body>
</html>

The problem here is that the {v: value, f: 'formatted value'} syntax is not valid for use with the arrayToDataTable method (as documented here(https://developers.google.com/chart/interactive/docs/reference#google.visualization.arraytodatatable) ). If you want to use that syntax, you will have to define your DataTable manually, and then use the #addRows method

Not sure why I had the error, but I found a way to get around it. It started working when I used the DataTable constructor:
var data = new google.visualization.DataTable();
data.addColumn('number', 'Price');
data.addColumn('number', 'Canon');
data.addColumn('number', 'Nikon');
data.addColumn('number', 'Other');
data.addRows([
[{v:6000, f: 'Canon EOS-1Ds Mark III'}, 60 ,null ,null],
[{v:5000, f: 'Canon EOS-1Ds Mark II'}, 50 ,null ,null],
Instead of the arraytoDataTable constructor:
var data = google.visualization.arrayToDataTable([
['Camera','Avg Rating'],
[ {v:6000, f: 'Canon EOS-1Ds Mark III'}, 60],
[ {v:5000, f: 'Canon EOS-1Ds Mark II'}, 50],
[ {v:4000, f: 'Canon EOS-1D Mark IV'}, 40]
]);
Hope that helps anybody who also runs into this.

Related

Label y-axis ticks with musical note name

I have a chart data table with series values as numbers (these are MIDI note numbers - e.g. 60 is middle C, 61 is Db).
But for the user, the chart y-axis ticks should be the note names.
How can I do that please?
using object notation, you can provide the value (v:) and the formatted value (f:) for each tick
{v: 60, f: 'C4 (middle C)'}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
[1, 60],
[2, 61]
], true);
var options = {
vAxis: {
ticks: [
{v: 60, f: 'C4 (middle C)'},
{v: 61, f: 'C#4/Db4'},
]
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Google Charts: Plotting mutiple "Y" values on same "X" value

I am using scatter plot of Google Charts.
This is what I currently have:
I am plotting values against named entities (On X axis). The entities can have multiple Blue/Red values. Referring to the screenshot above, I would like the blue dot to plot above A1, instead of A1 getting duplicated.
Can this be done?
Here is my code:
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Blue Value');
data.addColumn('number', 'Red Value');
data.addRows([
['A1', 3500, 4500],
['A1', 4000, null],
['A2', 3700, 4100],
['A3', 3110, 4200],
['A4', 3600, 4300]
]);
// Set chart options
var options = {'title':'My Title',
'width':800,
'height':500};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
by default, a discrete axis (string values) will show all x-axis values,
even if they repeat
to get the desired chart, you could use a continuous axis (number values),
and use object notation to format the values and the axis labels (ticks)
object notation allows you to provide both the value (v:) and the formatted value (f:)
{v: 1, f: 'A1'}
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Name');
data.addColumn('number', 'Blue Value');
data.addColumn('number', 'Red Value');
data.addRows([
[{v: 1, f: 'A1'}, 3500, 4500],
[{v: 1, f: 'A1'}, 4000, null],
[{v: 2, f: 'A2'}, 3700, 4100],
[{v: 3, f: 'A3'}, 3110, 4200],
[{v: 4, f: 'A4'}, 3600, 4300]
]);
var options = {
title: 'My Title',
width: 800,
height: 500,
hAxis: {
gridlines: {
color: 'transparent'
},
ticks: [
{v: 0.5, f: ''},
{v: 1, f: 'A1'},
{v: 2, f: 'A2'},
{v: 3, f: 'A3'},
{v: 4, f: 'A4'}
]
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Adding an HTML rendered title in Google Charts

I'm trying to create an HTML rendered title in Google Charts. I want to create a string variable that contains HTML code and then pass it on as the title of the chart. Here's a jsFiddle. Here's what I'm trying to do:
HTML
<div id="chart_div" style="width: 900px; height: 500px;"></div>
JS
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var ch = "<span>Hello World!</span>";
ch = $($.parseHTML(ch));
var options = {
title: ch
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
When I try outputting the string as a title, I get [object object]. I tried doing $($.parseHTML(ch)).html(); but it looks like this strips the HTML tags because when I add styling to the span element it doesn't style the title. What should I do to get an HTML string to be displayed as a title with styling?
the titleTextStyle option applies to the entire chart title,
it is not possible using standard config options to style only part of the title
it will also not accept html, since it is drawn using svg
you could use an adjacent <div> and leave the title out of the options,
or change the title's svg once the chart's 'ready' event fires...
the title will be in a svg <text> element,
to separate the title from the other <text> elements on the chart,
use an initial value that can be used to find it...
var options = {
title: 'chartTitle'
};
in the ready handler, find the element...
google.visualization.events.addListener(chart, 'ready', function () {
var chartTitle = $('#chart text').filter(':contains("chartTitle")')[0];
});
use the <tspan> element to style different parts of the <text> element
result may look something like this...
<text><tspan style="font-weight: bold;">Chart</tspan> Title</text>
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = new google.visualization.DataTable({
cols: [
{label: 'x', type: 'string'},
{label: 'y0', type: 'number'},
],
rows: [
{c:[{v: 'row 0'}, {v: 10}]},
{c:[{v: 'row 1'}, {v: 5}]},
{c:[{v: 'row 2'}, {v: 1}]},
{c:[{v: 'row 3'}, {v: 2}]},
{c:[{v: 'row 4'}, {v: 8}]}
]
});
var options = {
title: 'chartTitle'
};
var container = document.getElementById('chart');
var chart = new google.visualization.LineChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var svgNS = $('#chart svg')[0].namespaceURI;
var chartTitle = $('#chart text').filter(':contains("chartTitle")')[0];
$(chartTitle).text('');
var textStyle = document.createElementNS(svgNS, 'tspan');
$(textStyle).attr('fill', '#ff0000');
$(textStyle).attr('font-weight', 'bold');
$(textStyle).text('Chart ');
$(chartTitle).append(textStyle);
var textStyle = document.createElementNS(svgNS, 'tspan');
$(textStyle).attr('fill', '#0000ff');
$(textStyle).attr('font-weight', 'normal');
$(textStyle).text('Title');
$(chartTitle).append(textStyle);
});
chart.draw(data, options);
},
packages: ['corechart']
});
<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="chart"></div>
I'm not sure about editing it with HTML/CSS but you can use something that google-charts offers with titleTextStyle
var options = {
titleTextStyle: {
color: <string>, // any HTML string color ('red', '#cc00cc')
fontName: <string>, // i.e. 'Times New Roman'
fontSize: <number>, // 12, 18 whatever you want (don't specify px)
bold: <boolean>, // true or false
italic: <boolean> // true of false
}
}
Comes from this stack answer: Stack
Google Documentation here: Chart Customization

Add description in column chart by Google Charts?

I would like to replace "Step 1" in the screenshot below with the actual text in the table.
I think tooltip probably could help, but just didn't figure it out yet... Here is my code:
initGoolgeChart : function() {
// Load the Visualization API and the corechart package.
google.charts.load("current", {"packages": ["bar"] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(MigrationMonitor.drawCharts);
},
drawCharts : function() {
if(MigrationMonitor.dynamicFields.chartData != null && MigrationMonitor.dynamicFields.chartData.length > 0) {
var data = google.visualization.arrayToDataTable(MigrationMonitor.dynamicFields.chartData);
// won't work, don't know how i can add steps here then...
// data.addColumn({type:"string", role: "tooltip"});
// // Set chart options
var options = {
chart : {
title : "Build: " + MigrationMonitor.dynamicFields.chartTitle[1] + " VS " + MigrationMonitor.dynamicFields.chartTitle[2]
}
};
var chart = new google.charts.Bar(document.getElementById('charDiv'));
chart.draw(data, options);
}
}
use object notation to provide the value (v:) and formatted value (f:)
for the first column
the tooltip will display the formatted value (f:) by default
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Step', 'Build: 22850', 'Build: 22852'],
[{v: 'Step 1', f: 'Pre-migration tasks'}, {v: 66, f: '66 (s)'}, {v: 67, f: '67 (s)'}],
[{v: 'Step 2', f: 'Dropping SP, Triggers, Views, and Functions'}, {v: 6, f: '6 (s)'}, {v: 7, f: '7 (s)'}]
]);
var container = document.getElementById('chart_div');
var chart = new google.charts.Bar(container);
chart.draw(data);
},
packages: ['bar']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
if you're not able to provide the value using object notation, or it's just too inconvenient,
use the setFormattedValue method,
see following working snippet...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Step', 'Build: 22850', 'Build: 22852'],
['Step 1', 66, 67],
['Step 2', 6, 7]
]);
var formatNumber = new google.visualization.NumberFormat({
pattern: '0 (s)'
});
formatNumber.format(data, 1);
for (var i = 0; i < data.getNumberOfRows(); i++) {
switch (data.getValue(i, 0)) {
case 'Step 1':
data.setFormattedValue(i, 0, 'Pre-migration tasks');
break;
case 'Step 2':
data.setFormattedValue(i, 0, 'Dropping SP, Triggers, Views, and Functions');
break;
}
}
var container = document.getElementById('chart_div');
var chart = new google.charts.Bar(container);
chart.draw(data);
},
packages: ['bar']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
This can be easily accomplished if you could iterate the data and add to a blank google.visualization.DataTable
Simply initialize it like this:
var data = new google.visualization.DataTable()
Then you can add columns like this:
data.addColumn('number', 'time');
For the column that will be used for the ToolTip:
data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
Then you can add rows to this blank DataTable as follows:
dataTable.addRows([[10, 'tooltip for 10'], [20, 'tooltip for 20']]);
Probably your MigrationMonitor.dynamicFields.chartData will fit in there without the need to iterate.
Also there is an option tooltip: { isHtml: true } if you want to make tooltips HTML.
This is fully documented on the following link
https://developers.google.com/chart/interactive/docs/customizing_tooltip_content

Google charts and google table not displaying simultaneously

I am using google charts and google table for my project. The problem is that, I am not able to display two google charts and one google table on a single page. How can this be solved?
My code:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages': ['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?= $jsonTable ?>);
var options = {
title: ' Audit Schedule ',
is3D: 'true',
width: 500,
height: 250
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
width: 501.2,
height: 250
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['table']});
google.charts.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, true],
['Jim', {v: 8000, f: '$8,000'}, false],
['Alice', {v: 12500, f: '$12,500'}, true],
['Bob', {v: 7000, f: '$7,000'}, true]
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
</script>
//html code
<div id="piechart" style="margin-top: -300px; margin-left:490px;"></div><br>
<div class="chart-wrapper">
<div id="chart" style="width:1006px; height:400px; margin-left: -15px"></div>
</div><br>
<div id="table_div"></div>
Link to google charts: https://google-developers.appspot.com/chart/interactive/docs/gallery/columnchart#column-styles
You have defined multiple instances of google.charts.setOnLoadCallback(). This function should only be defined ONCE in your code, because otherwise you'll be overwriting the callback event everytime. Anyway, you should wrap all your chart drawing functions in something like :
function drawCharts(){
drawchart1();
drawchart2();
drawwhateveryouwant();
}
google.setOnLoadCallback(drawCharts);
Also, I might have to point out that you have two functions with the same name ^^, you might want to correct that. Other than that, you might want to call all your chart packages at once by doing this since I also noticed that you were loading the same package twice, which is a waste of resources even if it doesn't stop your code from functioning correctly :
google.load('visualization', '1', {'packages': ['corechart','table']});
I modified your code a bit to help you towards achieving desired results :
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
<div id="piechart"></div>
<div id="table_div"></div>
</body>
<script>
google.charts.setOnLoadCallback(init);
google.charts.load('current', {'packages':['corechart','table']});
//Function to draw piechart
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);
var options = {
title: 'My Daily Activities',
width: 501.2,
height: 250
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
};
//Function to draw table
function drawTable() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Salary');
data.addColumn('boolean', 'Full Time Employee');
data.addRows([
['Mike', {v: 10000, f: '$10,000'}, true],
['Jim', {v: 8000, f: '$8,000'}, false],
['Alice', {v: 12500, f: '$12,500'}, true],
['Bob', {v: 7000, f: '$7,000'}, true]
]);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true, width: '100%', height: '100%'});
}
//Function to initialize everything
function init(){
drawTable();
drawChart();
}
</script>
</html>
You'll forgive me for skipping the chart with JSON data though :p

Categories