google chart api material date month - google-visualization

I have a google bar chart with multiple series and a date hAxis.
My problem is that i want to show months only, but i get the label multiple times.
Here's an example
google.charts.load('current', {'packages': ['bar'], 'language': 'de'});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var chart;
var chartDiv = document.getElementById('test');
var data = new google.visualization.DataTable('{"cols":[{"type":"date","pattern":""},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"},{"type":"number"}],"rows":[{"c":[{"v":"Date(2016,2,1)"},{"v":2030,"f":"2030 km"},{"v":2098,"f":"2098 km"},{"v":1352,"f":"1352 km"},{"v":4412,"f":"4412 km"},{"v":132,"f":"132 km"},{"v":2435,"f":"2435 km"},{"v":3952,"f":"3952 km"}]},{"c":[{"v":"Date(2016,3,1)"},{"v":3177,"f":"3177 km"},{"v":2901,"f":"2901 km"},{"v":2491,"f":"2491 km"},{"v":1480,"f":"1480 km"},{"v":2272,"f":"2272 km"},{"v":400,"f":"400 km"},{"v":1096,"f":"1096 km"}]}]}');
var options = {
legend: { position: 'none' },
hAxis: {
type: 'category',
format: 'MMMM'
}
};
chart = new google.charts.Bar(chartDiv);
chart.draw(data, google.charts.Bar.convertOptions(options));
}
https://jsfiddle.net/1Lusd06n/3/
If i shrink the width of the fiddle, the month names are grouped and displayed once but this does not happen if there is more space.

Related

How to give api count and date value to google line chart?

I am making a simple web counter using count api. I am good in getting the counts. Now, I'm making a google line chart to show count value with the date in graph form. So, please help me how to set the date and count data in drawChart() function to get the count as per the date. And the graph should have 5 days of count. How to achieve this solution. Sincere Thanks in Advance!
const counter = document.getElementById('count');
updateVisitCount();
function updateVisitCount() {
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
counter.innerHTML = res.value;
});
}
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Date', 'Number of Site Visits'],
]);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
That's working.
var counters=[
['string', 'value'],
];
setInterval(()=>{
fetch('https://api.countapi.xyz/update/demo/sample/?amount=1').then(res => res.json())
.then(res => {
var dt = new Date();
var secs = dt.getSeconds()
counters.push(
[secs,res.value]
)
if(counters.length>3){
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
}
});
},1000);
function drawChart() {
var data = new google.visualization.arrayToDataTable(counters);
var options = {
title: 'Site Visits',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}

Google charts error:every row given must be either null or an array

I am working on a website that is intended to show some basic Google charts. The data comes from a text file that i retrieve through Ajax. It's got a x, y value and an annotation field. The data looks like this:
[[-0.8, -0.47, "100-005-10"],
[-0.7, -0.46, "100-005-9"],
[-0.6, -0.45, "100-005-8"],
[-0.5, -0.44, "100-005-7"]]
Here's my code:
<script >
var xmlhttp = new XMLHttpRequest();
var array;
xmlhttp.onreadystatechange = function() {
array = this.responseText;
};
xmlhttp.open("GET", "array.array", true);
xmlhttp.send();
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($.parseJSON(array), true)
data.addColumn('number', 'x');
data.addColumn('number', 'y');
data.addColumn({type: 'string', role: 'annotation'});
data.addRow(array);
var options = {
legend: 'none',
colors: ['#087037'],
selectionMode: 'single',
tooltip: {trigger: 'selection'},
pointSize: 12,
animation: {
duration: 200,
easing: 'inAndOut',
}
};
var chart = new google.visualization.ScatterChart(document.getElementById('animatedshapes_div'));
chart.draw(data, options);
}
</script>
When i run the code, i get this error message:
Error: If argument is given to addRow, it must be an array, or null
I just don't know how to transform the plain text from the ajax response to an array.
try using JSON.parse to convert the string to an actual array...
data.addRows(JSON.parse(array));
In one of the case, need to add Square brackets []
self.tableValues.forEach((row: any) => {
if(row) {
dataTable.addRows([row]); // <-- row is array; so try [row]
}
});

"Table has no rows" Error in Google Charts Histogram

I am working with Google Histogram chart. It working fine with some data sets but not for other data sets. And it raise an error "Table has no rows" even my input is correct.
Here i am reading a csv file column wise and pass to visualization page.
for eg: I am reading 2 csv column here and passing to visualization page. Here my input to Google histogram is
var inputdata1 = [["val","d"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","1"],["val","2"]];
and this working fine and gives histogram for me.
while I am passing other 2 columns.Here my input to Google histogram is
var inputdata2 = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
while executing this, it raise an error that "Table has no rows" . Please check my fiddle.
Any help would be greatly appreciated.
Thank you in Advance.
In fact neither inputdata1 nor inputdata2 contain JSON data that are supported by histogram chart.
According to the documentation the following formats are supported:
Data Format
There are two ways to populate a histogram datatable. When there's
only one series:
var data = google.visualization.arrayToDataTable([
['Name', 'Number'],
['Name 1', number1],
['Name 2', number2],
['Name 3', number3],
...
]);
...and when there are multiple series:
var data = google.visualization.arrayToDataTable([
['Series Name 1', 'Series Name 2', 'Series Name 3', ...],
[series1_number1, series2_number1, series3_number1, ...],
[series1_number2, series2_number2, series3_number2, ...],
[series1_number3, series2_number3, series3_number3, ...],
...
]);
Having said that you might want to convert the second column into number format:
var inputJson = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
var chartJson = inputJson.map(function(item,i){
if(i == 0)
return item;
else {
return [item[0],parseInt(item[1])];
}
});
var data = google.visualization.arrayToDataTable(chartJson);
Once the data is converted the chart will be rendered properly.
Working example
google.load('visualization', '1.1', {
'packages': ['corechart']
});
google.setOnLoadCallback(drawStuff);
function drawStuff() {
var inputJson = [["val","b"],["val","3"],["val","3"],["val","3"],["val","5"],["val","1"],["val","12"],["val","7"],["val","11"],["val","1"],["val","7"],["val","6"],["val","16"],["val","11"],["val","21"],["val","12"],["val","1"],["val","22"],["val","16"],["val","1"],["val","21"],["val","11"],["val","6"],["val","11"],["val","15"],["val","12"],["val","12"]];
var chartJson = inputJson.map(function(item,i){
if(i == 0)
return item;
else {
return [item[0],parseInt(item[1])];
}
});
var data = google.visualization.arrayToDataTable(chartJson);
//The below input data works fine.
//var data = google.visualization.arrayToDataTable([["val","d"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","1"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","2"],["val","1"],["val","2"]]);
// Set chart options
var options = {
width: 400,
height: 300,
histogram: {
bucketSize: 0.1
}
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.Histogram(document.getElementById('chart_div'));
chart.draw(data, options);
};
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script src="chart.js"></script>
<div id="chart_div"></div>

Combining two types of Category Filter in Google Charts API

I wanted to enable users to filter the results being displayed on the chart. Google API provides CategoryFilter which enforces filtering by rows. Here is my code which works perfectly fine
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['controls']});
// 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 countryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'negeri',
dataTable: data,
options: {
filterColumnLabel: 'Negeri',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true
}
},
// Define an initial state, i.e. a set of metrics to be initially selected.
state: {'selectedValues': ['Kedah', 'Johor']}
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Statistik Negeri vs. Kategori Sukan',
width: 1000,
height: 1000,
hAxis: {title: 'Negeri', titleTextStyle: {color: 'blue'}},
vAxis: {title: 'Jumlah Kategori', titleTextStyle: {color: 'blue'}}
}
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls so that:
// - the 'Country' selection drives the 'Region' one,
// - the 'Region' selection drives the 'City' one,
// - and finally the 'City' output drives the chart
bind(countryPicker, chart).
// Draw the dashboard
draw(data);
}
</script>
</head>
<body>
<div id="dashboard">
<div id="negeri"></div>
<div id="chart_div"></div>
</div>
</body>
</html>
However in my datatable, I would also want to filter by columns. These two types of filtering should work together. (dependent; by bind() function). I have referred to #asgallant http://jsfiddle.net/asgallant/WaUu2/ and that is the feature that I wanted to combine with.
How can I possibly combine them? I have tried combining setChartView() by #asgallant with google's dashboard() but it's not working.
<html>
<head>
<!--Load the Ajax API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['controls']});
// 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 columnsTable = new google.visualization.DataTable();
columnsTable.addColumn('number', 'colIndex');
columnsTable.addColumn('string', 'colLabel');
var initState= {selectedValues: []};
// put the columns into this data table (skip column 0)
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
// you can comment out this next line if you want to have a default selection other than the whole list
initState.selectedValues.push(data.getColumnLabel(i));
}
var countryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'negeri',
dataTable: data,
options: {
filterColumnLabel: 'Negeri',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true
}
},
// Define an initial state, i.e. a set of metrics to be initially selected.
state: {'selectedValues': ['Kedah', 'Johor']}
});
var columnFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'colFilter_div',
dataTable: columnsTable,
options: {
filterColumnLabel: 'colLabel',
ui: {
label: 'Kategori Sukan',
allowTyping: false,
allowMultiple: true,
allowNone: false,
selectedValuesLayout: 'belowStacked'
}
},
state: initState
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Statistik Negeri vs. Kategori Sukan',
width: 1000,
height: 1000,
hAxis: {title: 'Negeri', titleTextStyle: {color: 'blue'}},
vAxis: {title: 'Jumlah Kategori', titleTextStyle: {color: 'blue'}}
}
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the controls so that:
// - the 'Country' selection drives the 'Region' one,
// - the 'Region' selection drives the 'City' one,
// - and finally the 'City' output drives the chart
bind(countryPicker, columnFilter).
bind(columnFilter, chart).
// Draw the dashboard
draw(data);
}
</script>
</head>
<body>
<div id="dashboard">
<div id="negeri"></div>
<div id="chart_div"></div>
</div>
</body>
</html>
You want to bind your countryPicker filter to the chart as normal, but do not bind the columnFilter control to anything - the setChartView function handles everything for the columnFilter. You need to tweak a couple other lines to make it work with a dashboard, but nothing major. This is what it should look like:
function drawChart() {
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(<?=$jsonTable?>);
var columnsTable = new google.visualization.DataTable();
columnsTable.addColumn('number', 'colIndex');
columnsTable.addColumn('string', 'colLabel');
var initState= {selectedValues: []};
// put the columns into this data table (skip column 0)
for (var i = 1; i < data.getNumberOfColumns(); i++) {
columnsTable.addRow([i, data.getColumnLabel(i)]);
// you can comment out this next line if you want to have a default selection other than the whole list
initState.selectedValues.push(data.getColumnLabel(i));
}
var countryPicker = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'negeri',
dataTable: data,
options: {
filterColumnLabel: 'Negeri',
ui: {
labelStacking: 'vertical',
allowTyping: false,
allowMultiple: true
}
},
// Define an initial state, i.e. a set of metrics to be initially selected.
state: {'selectedValues': ['Kedah', 'Johor']}
});
var columnFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'colFilter_div',
dataTable: columnsTable,
options: {
filterColumnLabel: 'colLabel',
ui: {
label: 'Kategori Sukan',
allowTyping: false,
allowMultiple: true,
allowNone: false,
selectedValuesLayout: 'belowStacked'
}
},
state: initState
});
var chart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Statistik Negeri vs. Kategori Sukan',
width: 1000,
height: 1000,
hAxis: {title: 'Negeri', titleTextStyle: {color: 'blue'}},
vAxis: {title: 'Jumlah Kategori', titleTextStyle: {color: 'blue'}}
}
});
// Create the dashboard.
var dashboard = new google.visualization.Dashboard(document.getElementById('dashboard')).
bind(countryPicker, chart);
function setChartView () {
var state = columnFilter.getState();
var row;
var view = {
columns: [0]
};
for (var i = 0; i < state.selectedValues.length; i++) {
row = columnsTable.getFilteredRows([{column: 1, value: state.selectedValues[i]}])[0];
view.columns.push(columnsTable.getValue(row, 0));
}
// sort the indices into their original order
view.columns.sort(function (a, b) {
return (a - b);
});
chart.setView(view);
chart.draw();
}
google.visualization.events.addListener(columnFilter, 'statechange', setChartView);
var runOnce = google.visualization.events.addListener(dashboard, 'ready', function () {
google.visualization.events.removeListener(runOnce);
setChartView();
});
columnFilter.draw();
dashboard.draw(data);
}
google.load('visualization', '1', {packages:['corechart'], callback: drawChart});

How to show an Empty Google Chart when there is no data?

Consider drawing a column chart and I don't get any data from the data source, How do we draw an empty chart instead of showing up a red colored default message saying "Table has no columns"?
What I do is initialize my chart with 1 column and 1 data point (set to 0). Then whenever data gets added I check if there is only 1 column and that it is the dummy column, then I remove it. I also hide the legend to begin so that it doesn't appear with the dummy column, then I add it when the new column gets added.
Here is some sample code you can plug in to the Google Visualization Playground that does what I am talking about. You should see the empty chart for 2 seconds, then data will get added and the columns will appear.
var data, options, chart;
function drawVisualization() {
data = google.visualization.arrayToDataTable([
['Time', 'dummy'],
['', 0],
]);
options = {
title:"My Chart",
width:600, height:400,
hAxis: {title: "Time"},
legend : {position: 'none'}
};
// Create and draw the visualization.
chart = new google.visualization.ColumnChart(document.getElementById('visualization'));
chart.draw(data,options);
setTimeout('addData("12:00",10)',2000);
setTimeout('addData("12:10",20)',3000);
}
function addData(x,y) {
if(data.getColumnLabel(1) == 'dummy') {
data.addColumn('number', 'Your Values', 'col_id');
data.removeColumn(1);
options.legend = {position: 'right'};
}
data.addRow([x,y]);
chart.draw(data,options);
}​
A even better solution for this problem might be to use a annotation column instead of a data column as shown below. With this solution you do not need to use any setTimeout or custom function to remove or hide your column. Give it a try by pasting the given code below into Google Code Playground.
function drawVisualization() {
var data = google.visualization.arrayToDataTable([
['', { role: 'annotation' }],
['', '']
]);
var ac = new google.visualization.ColumnChart(document.getElementById('visualization'));
ac.draw(data, {
title : 'Just a title...',
width: 600,
height: 400
});
}
​
The way I did this was by disabling the pie slices, turning off tooltips, stuffing in a pretend value and making it gray. I'm sure there are more clever ways to do this, but this worked for me where the other methods didn't.
The only drawback is that it sets both items in the legend to gray as well. I think you could perhaps just add a third item, and make it invisible on the legend only. I liked this way though.
function drawChart() {
// Define the chart to be drawn.
data = new google.visualization.DataTable();
data.addColumn({type: 'string', label: 'Result'});
data.addColumn({type: 'number', label: 'Count'});
data.addRows([
['Value A', 0],
['Value B', 0]
]);
var opt_pieslicetext = null;
var opt_tooltip_trigger = null;
var opt_color = null;
if (data.getValue(1,1) == 0 && data.getValue(0,1) == 0) {
opt_pieslicetext='none';
opt_tooltip_trigger='none'
data.setCell(1,1,.1);
opt_color= ['#D3D3D3'];
}
chart = new google.visualization.PieChart(document.getElementById('mydiv'));
chart.draw(data, {sliceVisibilityThreshold:0, pieSliceText: opt_pieslicetext, tooltip: { trigger: opt_tooltip_trigger }, colors: opt_color } );
}