Google Visualization Chart Data Range - charts

I have this code,
<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 query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1ntnhvfMhYtFNwFjkoKu8cUZOQPCaT5_U1Z6piB_w0-E/edit#gid=0');
query.setQuery('order by A');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var options = {
title: 'TEMP & HUMID',
hAxis: {
direction: -1
},
legend: 'none'
};
var data = response.getDataTable();
var chart = new google.visualization.LineChart(document.getElementById('columnchart'));
chart.draw(data, options);
}
</script>
<title>Data from a Spreadsheet</title>
</head>
<body>
<div id="columnchart" style="width: 900px; height: 500px"></div>
</body>
</html>
And here is my spreadsheet data: https://docs.google.com/spreadsheets/d/1ntnhvfMhYtFNwFjkoKu8cUZOQPCaT5_U1Z6piB_w0-E
What I want to do is to plot last 5 data. i.e) row 8 - 12 in my spreadsheet.
I tried the limit and range queries, but what I want to do is, if a new data comes in, I want the chart to refer the updated last 5 data i.e) row 9 -13
How could I achieve this?

I don't know if this is a best approach, but I work it out.
So, before drawing the table, I actually called the spreadsheet in JSON format and retrieve its column length.
Then I subtracted the column length by number of data I want to display (limit query) which will give me offset to start.
Then I made a string with the value of limit and offset to pass the query option to query.setQuery.
Here is the code for the part.
function drawChart() {
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1NSEbUWojJsMzhH0hi8kx8ic7Xxuq29z0c7BXs-inzb8/edit#gid=0');
$.getJSON("https://spreadsheets.google.com/feeds/list/1NSEbUWojJsMzhH0hi8kx8ic7Xxuq29z0c7BXs-inzb8/od6/public/basic?hl=en_US&alt=json", function(data) {
colLen = data.feed.entry.length;
console.log(colLen);
limit = 4;
var offset = colLen - limit;
console.log(offset);
queryOption = "limit "+limit+" offset "+offset;
console.log(queryOption);
query.setQuery(queryOption);
query.send(handleQueryResponse);
});
}

Related

google charts - data from csv - date format

In a webpage I load data from a csv file that contains like (it can contains months of data) :
timestamp,open,high,low,close
2022-08-03,1.01554,1.02105,1.01210,1.01618
2022-08-02,1.02578,1.02939,1.01619,1.01625
2022-08-01,1.02182,1.02753,1.02040,1.02587
2022-07-29,1.01952,1.02544,1.01440,1.02248
2022-07-28,1.02005,1.02344,1.01120,1.01947
2022-07-27,1.01174,1.02209,1.00950,1.01998
2022-07-26,1.02210,1.02502,1.01060,1.01179
2022-07-25,1.02174,1.02579,1.01770,1.02200
The first column is a date, but I think the google chart treat it like a string while creating the chart.
This is the code in html page I use to load data from csv and to create the chart:
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="jquery.csv-0.71.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script>
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
</script>
<script>
function drawVisualization() {
$.get("EURUSD.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
// this new DataTable object holds all the data
var data = new google.visualization.arrayToDataTable(arrayData);
var view = new google.visualization.DataView(data);
//view.setColumns([0,1]);
var options = {
legend: 'none',
title: 'EURUSD',
bar: { groupWidth: '100%' }, // Remove space between bars.
candlestick: {
fallingColor: { strokeWidth: 0, fill: '#a52714' }, // red
risingColor: { strokeWidth: 0, fill: '#0f9d58' } // green
}
};
var chart = new google.visualization.CandlestickChart(document.getElementById('chart_div'));
data.sort({column: 0, asc: true});
chart.draw(data, options);
});
}
google.setOnLoadCallback(drawVisualization)
</script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
enter code here
The chart I get is:
I would like to group by month or by year in the X asses, insted of everyday date printed there.
How can I do?
Thank You
Carlo
after you load the csv data...
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
convert the first column to a date...
arrayData = arrayData.map(function (row) {
row[0] = new Date(row[0]);
return row;
});

How to draw date in x-axis in Area Chart?

I have the following data in a Google Spreadsheet:
ColumnA ColumnB
Departament Quantity
01/01/2016 23
02/01/2016 43
04/01/2016 5
06/01/2016 65
10/01/2016 12
11/01/2016 32
13/01/2016 22
15/02/2016 2
And want to draw a linechart using HTML Templates: This is my code so far now
<!DOCTYPE html>
<html>
<head>
<script src="https://www.google.com/jsapi"></script>
</head>
<body>
<div id="main"></div>
<script>
google.load('visualization', '1', {packages: ['corechart', 'bar']});
google.setOnLoadCallback(getSpreadsheetData);
function getSpreadsheetData() {
google.script.run.withSuccessHandler(drawChart).getSpreadsheetData();
}
function drawChart(rows) {
var options = {'title':'Example','width':400,'height':300};
var data = google.visualization.arrayToDataTable(rows, false);
var chart = newgoogle.visualization.LineChart(document.getElementById("main"));
chart.draw(data, options)
}
</script>
</body>
</html>
My script to read the sheet:
function getSpreadsheetData() {
var ssID = "12GvIStMKqmRFNBM-C67NCDeb89-c55K7KQtcuEYmJWQ",
sheet = SpreadsheetApp.openById(ssID).getSheets()[0],
data = sheet.getDataRange().getValues();
return data;
}
However i cant draw the plot, this issue dissapear when i change the data to a numeric (i.e. 42370), but thats not what i want!
Question is: what do i have to add in order to change to the right format in x axis?
You can use the hAxis.format configuration option
var options = {'title':'Example','width':400,'height':300,//-->'format':'MM/dd/yyyy'};
The valid format options can be found here...
And if you need to load with a specific locale, see this...

How to display the value (sum) rather than count of markers in a dc.leaflet.js

I want to use crossfilter's reduceSum function dc.leaflet.js, and display the sum instead of the number of clustered markers.
The first example for dc.leaflet.js uses reduceCount. Additionally it doesn't use the reduced value; it just displays the number of markers in the cluster.
I want to use the sum of data using reduceSum.
Here is my data as tsv:
type geo say
wind 38.45330,28.55529 10
wind 38.45330,28.55529 10
solar 39.45330,28.55529 10
Here is my code:
<script type="text/javascript" src="../js/d3.js"></script>
<script type="text/javascript" src="../js/crossfilter.js"></script>
<script type="text/javascript" src="../js/dc.js"></script>
<script type="text/javascript" src="../js/leaflet.js"></script>
<script type="text/javascript" src="../js/leaflet.markercluster.js"></script>
<script type="text/javascript" src="../js/dc.leaflet.js"></script>
<script type="text/javascript">
/* Markers */
d3.csv("demo1.csv", function(data) {
drawMarkerSelect(data);
});
function drawMarkerSelect(data) {
var xf = crossfilter(data);
var facilities = xf.dimension(function(d) { return d.geo; });
var facilitiesGroup = facilities.group().reduceSum(function(d){return d.say});
dc.leafletMarkerChart("#demo1 .map")
.dimension(facilities)
.group(facilitiesGroup)
.width(1100)
.height(600)
.center([39,36])
.zoom(6)
.cluster(true);
var types = xf.dimension(function(d) { return d.type; });
var typesGroup = types.group().reduceSum(function(d){return d.say});
dc.pieChart("#demo1 .pie")
.dimension(types)
.group(typesGroup)
.width(200)
.height(200)
.renderLabel(true)
.renderTitle(true)
.ordering(function (p) {
return -p.value;
});
dc.renderAll();
}
</script>
I have rewritten the question because it was very unclear. I agree with #Kees that the intention was probably to display the sum in a clustered marker chart, rather than "reduceSum doesn't work".
#Kees also pointed out a Leaflet.markercluster issue which gives basic information about how to display a sum inside a marker cluster.
The question becomes, how to apply these customizations to dc.leaflet.js?
First, I've created a version of the example data with another column rnd:
type geo rnd
wind 43.45330,28.55529 1.97191
wind 43.44930,28.54611 3.9155
wind 43.45740,28.54814 3.9922
...
We can use reduceSum like this:
var facilitiesGroup = facilities.group().reduceSum(d => +d.rnd);
And annotate each marker with its value by overriding .marker(), wrapping the default callback:
const old_marker_function = marker.marker();
marker.marker(function(d, map) {
const m = old_marker_function(d, map);
m.value = d.value;
return m;
});
And we can specify a different rendering of the icon using .clusterOptions():
marker.clusterOptions({
iconCreateFunction: function(cluster) {
var children = cluster.getAllChildMarkers();
var sum = 0;
for (var i = 0; i < children.length; i++) {
sum += children[i].value;
}
sum = sum.toFixed(0);
var c = ' marker-cluster-';
if (sum < 10) {
c += 'small';
} else if (sum < 100) {
c += 'medium';
} else {
c += 'large';
}
return new L.DivIcon({ html: '<div><span>' + sum + '</span></div>', className: 'marker-cluster' + c, iconSize: new L.Point(40, 40) });
}
});
The example given in the above issue was missing any styling, so I copied the implementation of _defaultIconCreateFunction from the Leaflet.markercluster sources, and modified it.
Demo fiddle
As expected, the numbers are close to 2.5 times the original numbers (since the new column is a random number from 0 to 5).
Putting numbers on the individual markers
marker.icon() allows you change the icon for individual markers, so you can use DivIcon with similar styling to display the numbers:
marker.icon(function(d, map) {
return new L.DivIcon({
html: '<div><span>' + d.value.toFixed(0) + '</span></div>',
className: 'marker-cluster-indiv marker-cluster',
iconSize: new L.Point(40, 40) });
});
This introduces a new class .marker-cluster-indiv to distinguish it from the others; in the new fiddle I've colored them blue with
.marker-cluster-indiv {
background-color: #9ecae1;
}
.marker-cluster-indiv div {
background-color: #6baed6;
}
The interaction is perhaps less clear since clicking blue dots brings up a popup instead of expanding. Perhaps a different icon should be used.
The reduceSum part should work fine, since that is just a different crossfilter function.
Are you sure that your data is getting read correctly? You state that it is a tsv file, and show code that looks like it is tab-separated, but then you use d3.csv to load it, which would have pretty bad effects considering there is a comma in the middle of the second field.
Please try console.log(data) after your data is loaded, and verify that it is loading correctly.
Also, you do not state what problem you encounter. "It doesn't work" does not help us help you.

Add tooltips to a Google Line Chart with multiple data series - with simplified test case and screenshot

I have a Google Line Chart with 2 data series - Row A and Row B:
Here is the very simple test code - just open it in the browser and it will work:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<script type="text/javascript">
var data = {"rows":[
{"c":[{"v":"C"},{"v":-43},{"v":-42}]},
{"c":[{"v":"D"},{"v":-49},{"v":-39}]},
{"c":[{"v":"E"},{"v":-49},{"v":-48}]},
{"c":[{"v":"F"},{"v":-50},{"v":-49}]},
{"c":[{"v":"G"},{"v":-57},{"v":-56}]}],
"cols":[
{"p":{"role":"domain"},"label":"MEASUREMENT","type":"string"},
{"p":{"role":"data"},"label":"Row A","type":"number"},
{"p":{"role":"data"},"label":"Row B","type":"number"}]};
function drawCharts() {
var x = new google.visualization.DataTable(data);
var options = {
title: 'How to add tooltips?',
width: 800,
height: 600
};
var chart = new google.visualization.LineChart(document.getElementById('test'));
chart.draw(x, options);
}
$(function() {
google.setOnLoadCallback(drawCharts);
});
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
I would like to add tooltips to each data point, which would for example display:
Row A: x=D y=-49
on mouse hover. And I can not use dataTable.addColumn, because my chart is generated at once by a perl script and I just use a data Object with cols and rows as above.
Does anybody please know, how to do it here?
You can use a DataView to create the tooltip columns for you. This code snippet will dynamically create a tooltip column in the DataView for every data series:
var columns = [0];
for (var i = 1; i < x.getNumberOfColumns(); i++) {
columns.push(i);
columns.push({
type: 'string',
properties: {
role: 'tooltip'
},
calc: (function (j) {
return function (dt, row) {
return dt.getColumnLabel(j) + ': x=' + dt.getValue(row, 0) + ' y=' + dt.getValue(row, j)
}
})(i)
});
}
var view = new google.visualization.DataView(x);
view.setColumns(columns);
See the working example here: http://jsfiddle.net/asgallant/xWwxP/

Interval role i-lines are not displayed in Google line chart

I am trying to add min and max limits to a Google chart, which I generate using a Perl script from CSV data - by using the interval role for these 2 values.
Unfortunately the I-lines are not displayed at my line chart, even though I've set the min and max limits to the -100 and 100 for the sake of testing.
Only the main data is being displayed:
Can anybody please spot the error, what is wrong with my very simple test case?
Please just save the code below as an HTML-file and open in a browser:
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1','packages':['corechart']}]}"></script>
<script type="text/javascript">
var data = {"L_B8_ACLR_50_0_QPSK_1_H":{"rows":[
{"c":[{"v":"UTRA_1_DOWN"},{"v":-100},{"v":100},{"v":"-42.46912"}]},
{"c":[{"v":"E-UTRA_1_DOWN"},{"v":-100},{"v":100},{"v":"-39.9545"}]},
{"c":[{"v":"E-UTRA_1_UP"},{"v":-100},{"v":100},{"v":"-48.68408"}]},
{"c":[{"v":"UTRA_1_UP"},{"v":-100},{"v":100},{"v":"-49.45148"}]},
{"c":[{"v":"UTRA_2_UP"},{"v":-100},{"v":100},{"v":"-58.96674"}]}],
"cols":[
{"p":{"role":"domain"},"label":"MEASUREMENT","type":"string"},
{"p":{"role":"interval"},"label":"LSL","type":"number"},
{"p":{"role":"interval"},"label":"USL","type":"number"},
{"p":{"role":"data"},"label":"1142926087","type":"number"}]}};
function drawCharts() {
for (var csv in data) {
var x = new google.visualization.DataTable(data[csv]);
var options = {
title: csv,
width: 800,
height: 600
};
var chart = new google.visualization.LineChart(document.getElementById(csv));
chart.draw(x, options);
}
}
$(function() {
google.setOnLoadCallback(drawCharts);
});
</script>
</head>
<body>
<div id="L_B8_ACLR_50_0_QPSK_1_H"></div>
</body>
</html>
(I don't want to use methods like addColumn or addRows. Instead I prepare my data as data structure in my Perl script and then JSON-encode and pass it to DataTable ctr).
You must specify the interval-role column after the data-column. As written in the API :
"All columns except domain columns apply to the nearest left neighbor to which it can be applied"
So if you change the order (and here with some smaller intervals)
var data = {"L_B8_ACLR_50_0_QPSK_1_H":{"rows":[
{"c":[{"v":"UTRA_1_DOWN"},{"v":"-42.46912"},{"v":-50},{"v":-45}]},
{"c":[{"v":"E-UTRA_1_DOWN"},{"v":"-39.9545"},{"v":-50},{"v":-45}]},
{"c":[{"v":"E-UTRA_1_UP"},{"v":"-48.68408"},{"v":-50},{"v":-45}]},
{"c":[{"v":"UTRA_1_UP"},{"v":"-49.45148"},{"v":-50},{"v":-45}]},
{"c":[{"v":"UTRA_2_UP"},{"v":"-58.96674"},{"v":-50},{"v":-45}]}],
"cols":[
{"p":{"role":"domain"},"label":"MEASUREMENT","type":"string"},
{"p":{"role":"data"},"label":"1142926087","type":"number"},
{"p":{"role":"interval"},"label":"LSL","type":"number"},
{"p":{"role":"interval"},"label":"USL","type":"number"}
]}};
..You end up with :