I'm trying to create charts using Google Charts Api. My data is stored as a json file as shown.
{
"1":[{"a":0,"d":0}],
"2":[{"a":0,"d":0}],
"3":[{"a":6,"d":62.92}],
"4":[{"a":1.57,"d":75.32}],
"5":[{"a":1.67,"d":66.45}],
"6":[{"a":1.25,"d":76}],
"7":[{"a":1.36,"d":75.08}],
"8":[{"a":1.59,"d":69.27}],
...
}
I'm fetching json file, pushing the objects to a javascript array. It works with no problem. I added these lines to understand what's happening. However Google Api doesn't accept my values and shows only
dots.push([5, 50]);
dots.push([7,60]);
Here's my code
function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');
dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);
$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});
});
data.addRows(dots);
var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Data type of the values are number, I also tried eval() to. In console, values are seems in array. Can't understand what's wrong.
Here's the console log of dots and data with a screen shot.
The problem is with the asynchronous getJSON call. The getJSON call happens but while it's still retrieving the contents of graph.json, the rest of the code executes. This means that the getJSON callback runs after the chart has been drawn.
Solution: Move the chart drawing code into the getJSON callback:
function drawDots()
{
var data = new google.visualization.DataTable();
data.addColumn('number', 'a');
data.addColumn('number', 'd');
dots = new Array;
dots.push([5, 50]);
dots.push([7,60]);
$.getJSON("/graph/graph.json", function(json)
{
$.each(json, function(id, num)
{
$.each(num, function(i, e)
{
dots.push([e.a, e.d]);
});
});
data.addRows(dots);
var options = {
title: '',
hAxis: {title: 'Data 1', minValue: 0, maxValue: 100},
vAxis: {title: 'Data 2', minValue: 0, maxValue: 100},
legend: 'none'
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
}
Related
I have a Google Chart (column-chart) showing a single dated (Jan-2010 = 2010-01-01) column - but the resulting column seems to run from 1-Jul-09 through to 1-Jul-10 (note this seems to change depending on the width of the screen); how can I fix this so that the column sits only on the 01-Jan-2010 date? (**Note, the dates/values are variable and can include one or hundreds of column values so we CANNOT simply hard code this or change the column type from 'date' to 'string').
var arr = eval("[[new Date(2010, 0, 1), 0,1]]");
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dt');
data.addColumn('number', 'Open');
data.addColumn('number', 'Closed');
data.addRows(arr);
var options_stacked = {
isStacked: true,
height: 300,
colors: ['#111', '#a00'],
hAxis: {
slantedText: false,
format: 'd/MMM/yy',
},
legend: {
position: 'top',
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options_stacked);
A demonstrator for this can be found on https://jsfiddle.net/Abeeee/d5fojtp2/34/
you can add custom ticks to ensure each column "sits" on the correct date.
the ticks option expects an array of values.
we can use DataTable method --> getDistinctValue(colIndex)
to return the date values from the data table.
var xTicks = data.getDistinctValues(0);
hAxis: {
slantedText: false,
format: 'd.MMM.yy', <---- changed from 'd/MMM/yy' to avoid line breaks
ticks: xTicks
},
see following working snippet...
function doTest() {
var arr = eval("[[new Date(2010, 0, 1), 0,1]]");
var data = new google.visualization.DataTable();
data.addColumn('date', 'Dt');
data.addColumn('number', 'Open');
data.addColumn('number', 'Closed');
data.addRows(arr);
var xTicks = data.getDistinctValues(0);
var options_stacked = {
isStacked: true,
height: 300,
colors: ['#111', '#a00'],
hAxis: {
slantedText: false,
format: 'd/MMM/yy',
ticks: xTicks
},
legend: {
position: 'top',
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options_stacked);
}
window.addEventListener('resize', doTest);
google.charts.load('current', {
packages: ['corechart', 'bar']
});
google.charts.setOnLoadCallback(doTest);
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<h1>Google Charts</h1>
<div id="chart_div"></div>
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
I have a google chart as follows which plots Age for various IDs. However, as age cannot be negative, I want it to be only on the positive axis.
I have given the minValue for vertical axis as 0, however it still shows the negative axis. How can I fix this?
My code below
function AgeChart() {
google.load("visualization", "1", {packages:["corechart"]});
var age_data = new google.visualization.DataTable();
var divname = "agediv";
age_data.addColumn('number', 'ID');
age_data.addColumn('number', 'Age');
age_data.addRow([1,10]);
age_data.addRow([1,20]);
age_data.addRow([1,30]);
age_data.addRow([1,40]);
age_data.addRow([1,50]);
var options = {'title':'Age line graph',
curveType: 'function',
viewWindowMode:'explicit',
vAxis: {title: 'Age (years)',
minValue: 0,
},
hAxis: {title: 'ID'},
height: 600,
width: 1000
};
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(age_data, options);
}
EDIT: After adding the viewWindow.min value, it works for me.
function AgeChart() {
google.load("visualization", "1", {packages:["corechart"]});
var age_data = new google.visualization.DataTable();
var divname = "agediv";
age_data.addColumn('number', 'ID');
age_data.addColumn('number', 'Age');
age_data.addRow([1,10]);
age_data.addRow([1,20]);
age_data.addRow([1,30]);
age_data.addRow([1,40]);
age_data.addRow([1,50]);
var options = {'title':'Age line graph',
curveType: 'function',
viewWindowMode:'explicit',
vAxis: {title: 'Age (years)',
minValue: 0,
viewWindowMode:'explicit',
viewWindowMode:'explicit',
viewWindow:{
min:0,
}
},
hAxis: {title: 'ID'},
height: 600,
width: 1000
};
var chart = new google.visualization.LineChart(document.getElementById(divname));
chart.draw(age_data, options);
}
The minValue and maxValue may be used to extend the axis to include those values, but they do not restrict the axis to those values. What you want to do instead is use the viewWindow.min value.
On the date 26/10/2015 the actual version of Google charts requires only the following to stop displaying the negatives on the vertical axis.
var options = {
hAxis: { title: 'Dates',
},
vAxis: { title: 'Count of something',
viewWindow:{min:0},
},
};
As an option you can set up min value for more than 0 - it will give you same view.
vAxis: { title: 'Count',
minValue: 2,
},
I was looking through the API and couldn't find anything about getting the type of chart.
I have this code:
<script type="text/javascript">
var chart;
function drawTest( dataTable ) {
google.load("visualization", "1", {packages:["corechart"]});
var options = {
title: 'test chart',
hAxis: {title: 'Day', titleTextStyle: {color: 'black'},
animation: {
duration: 1000,
easing: 'out',
}}
};
var data = new google.visualization.DataTable();
data.addColumn('string', 'String');
data.addColumn('number', 'Number1');
data.addColumn('number', 'Number2');
dataTable.forEach( function(row) {
data.addRow( row );
} );
chart = new google.visualization.ColumnChart( document.getElementById( 'chart' ) );
chart.draw( data, options );
}
What I want to do is instead of setting chart to a new chart in the bottom I want to check if it's already set. I'm not sure if this is in the API.
if( chart.getType() == "ColumnChart" ){
chart.draw( data, options );
}
However, I have multiple charts so I can't just check if chart is initialized.
Any help about completing this task is appreciated.
If you use a chartWrapper instead, there is a getChartType method that returns the class name of the wrapped chart. You can view more info about chartWrapper class here:
https://developers.google.com/chart/interactive/docs/reference#chartwrapperobject
Here is an example using google visualization playground:
function drawVisualization() {
// Create and populate the data table.
var wrapper = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
dataTable: [['', 'Germany', 'USA', 'Brazil', 'Canada', 'France', 'RU'],
['', 700, 300, 400, 500, 600, 800]],
options: {'title': 'Countries'},
containerId: 'visualization'
});
wrapper.draw();
console.log(wrapper.getChartType()) // ColumnChart
}
Consider the following code:
google.load("visualization", "1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.DataTable();
data.addColumn('datetime', 'Time');
data.addColumn('number', 'Leads');
data.addRow([Date.parse("2013-08-17 10:12:18"), 0]);
data.addRow([Date.parse("2013-08-17 09:13:42"), 14]);
data.addRow([Date.parse("2013-08-17 10:00:05"), 15]);
data.addRow([Date.parse("2013-08-17 11:12:18"), 3]);
var options = {
title: 'Company Performance',
fontSize: '12px',
curveType: 'function',
pointSize: 5,
hAxis: {
title: 'Daily Report',
titleTextStyle: {
color: '#FF0000'
}
},
vAxis: {
title: 'Leads',
titleTextStyle: {
color: '#FF0000'
}
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
Now, the above code is suppsed to load google chart api, defined a DataTable & generate a LineChart graph but it doesn't. Instead, I the following error when trying to add Columns
TypeError: data is undefined #at this line --> data.addColumn('datetime', 'Time')
Can anyone tell me what am I missing?
you did not use new while creating a new object of google.visualization.Datatable.
function drawChart() {
// var data = google.visualization.DataTable(); missed new keyword
var data = new google.visualization.DataTable();
//...
}