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;
});
Related
How can plot a Google Scatterchartfrom an uploaded csv file?
It is showing a blank page.
I tried the following code:
Loading the scripts:
<script src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
Then I got this part from an example:
<script> // wait till the DOM is loaded
$(function() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.csv", function(csvString) {
// display the contents of the CSV
$("#chart").html(csvString); }); });
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.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);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data); view.setColumns([0,1]);
var options = {};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
}); }
</script>
the example has an error.
the brackets at the end of the following line...
$("#chart").html(csvString); }); }); <-- these two sets of brackets
need to move down below the rest of the code,
here is the full, corrected snippet...
$(function() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.csv", function(csvString) {
// display the contents of the CSV
$("#chart").html(csvString);
// load the visualization library from Google and set a listener
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("https://www.batemo.de/wp-content/uploads/general/data_chart_gravimetric.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);
// this view can select a subset of the data at a time
var view = new google.visualization.DataView(data); view.setColumns([0,1]);
var options = {};
var chart = new google.visualization.ScatterChart(document.getElementById('chart'));
chart.draw(view, options);
}); }
}); });
I'm trying to draw a Google Chart whose x-axis represents the week numbers. As we're crossing a new year, the axis goes 50, 51, 52, 1, 2, 3, ....
I'm properly ordering my data, but Google Charts insists on reordering my x-axis, and I end up with a weird graph:
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
google.load("visualization", "1", {
packages:["corechart"],
callback: function() {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable);
}});
<div id="chart" style="height: 400px;">test</div>
<script src="//www.google.com/jsapi"></script>
How can I prevent it from reordering my data?
google's object notation allows you to provide a value (v:) and a formatted value (f:)
thus, you can use a value of 1 with a format of '40'
e.g. --> {v: 1, f: '40'}
in a row --> [{v: 1, f: '40'},227]
the following working snippet uses object notation to re-format the values for the x-axis,
and re-use those values for the x-axis labels (hAxis.ticks)
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
var hAxisTicks = [];
chartData.forEach(function (row, index) {
if (index === 0) {
return;
}
row[0] = {
v: index,
f: row[0].toString()
};
hAxisTicks.push(row[0]);
});
google.charts.load('current', {
callback: function () {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable, {
hAxis: {
ticks: hAxisTicks
}
});
},
packages:['corechart']
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
note:
recommend using loader.js to load the the library, instead of jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader from now on.
this only changes the load statement, see snippet above...
EDIT:
there are more options available for continuous axis
which must be sorted, or in reverse sort order ('number', 'date' values)
but the chart will respect the original sort order for a discrete axis ('string' values)
see following snippet for 'string' values
and discrete vs. continuous for more...
var chartData = [
["Week","Revenue"],
[40,227],
[41,317],
[42,320],
[43,482],
[44,418],
[45,345],
[46,313],
[47,316],
[48,380],
[49,467],
[50,349],
[51,256],
[52,393],
[1,276],
[2,349],
[3,312]
];
chartData.forEach(function (row, index) {
if (index === 0) {
return;
}
row[0] = row[0].toString();
});
google.charts.load('current', {
callback: function () {
var div = document.getElementById('chart');
var chartDataTable = google.visualization.arrayToDataTable(chartData);
var chart = new google.visualization['LineChart'](div);
chart.draw(chartDataTable);
},
packages:['corechart']
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>
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);
});
}
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/
I'm implementing the classic mercator example (https://github.com/mbostock/d3/blob/master/examples/mercator/mercator.html), which I've changed to zoom into Afghanistan and to use only one custom slider. I'm reading in GeoJSON data of places where explosions have happened and the graph maps them all at load. I want to use the slider to view only a month of explosion points at a time but am having trouble filtering the results. I've tried several things based on posts in the Google group but fail to understand how to filter the data read in previously from 'explosions.json'. Thanks for the help!
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>IED Attacks in Afghanistan (2004-2009)</title>
<script type="text/javascript" src="../d3.v2.js"></script>
<script type="text/javascript" src="../lib/jquery/jquery.min.js"></script>
<script type="text/javascript" src="../lib/jquery-ui/jquery-ui.min.js"></script>
<style type="text/css">
#import url("../lib/jquery-ui/jquery-ui.css");
body, .ui-widget {
font: 14px Helvetica Neue;
}
svg {
width: 960px;
height: 600px;
border: solid 1px #ccc;
background: #eee;
}
line {
stroke: brown;
stroke-dasharray: 4,2;
}
path {
fill: #ccc;
stroke: #fff;
}
div {
width: 960px;
}
</style>
</head>
<body>
<h3>IED Attacks in Afghanistan (2004-2009)</h3>
<script type="text/javascript">
// Create the Mercator Projection (Map)
var xy = d3.geo.mercator(),
path = d3.geo.path().projection(xy);
// Create the states variable
var states = d3.select("body")
.append("svg")
.append("g")
.attr("id", "states");
// Create the equator variable
var equator = d3.select("svg")
.append("line")
.attr("x1", "0%")
.attr("x2", "100%");
// Create the explosions variable
var explosions = d3.select("svg")
.append("g")
.attr("id","explosions");
// Load in the states & equator data from the file 'world-countries.json'
d3.json("world-countries.json", function(collection) {
states
.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("d", path)
.append("title")
.text(function(d) { return d.properties.name; });
equator
.attr("y1", xy([0, 0])[1])
.attr("y2", xy([0, 0])[1]);
});
// the variable that holds our translate, center on Afghanistan
var translate = xy.translate(); //create translation to center gride in different area
translate[0] = -1741;
translate[1] = 1487;
xy.translate(translate); // center
xy.scale(12000); //zoom in
// Load in the explosions data from the file 'explosions.json'
d3.json("explosions.json", function(collection) {
explosions
.selectAll("path") //make a path and attach data
.data(collection.features)
.enter().append("path")
.attr("d", path)
.style("stroke","red") //color the path points
.style("stroke-width",2) //size of point stroke
.attr("class","explosionpoint")
.append("title") //title is the 'name' field in the json file
.text(function(d) { return d.properties.name; });
});
</script>
<p></p>
<!-- Slider -->
<div id="scale"></div><p></p>
<script type="text/javascript">
$("#scale").slider({
min: 20040101, //min : 1/1/04
max: 20100101, //max: 1/1/10
value: 20060601, //default slider value
step: 100, // step is the allow increments the slider can move. 100 = one month
slide: function(event, ui) {
/* REMOVE ALL EXPLOSION PATHS EXCEPT FOR A PARTICULAR MONTH OR RELOAD WITH FILTERED RESULTS */
}
});
</script>
You'll need to post part or all of your explosions.json object for a concrete answer. However, something like this will filter a JSON if it's structured like {explosion1:{data1:true, data2:true}, explosion2:{data1:true, data2:false}}:
function filterJSON(json, key, value) {
var result = {};
for (var explosionIndex in json) {
if (json[explosionIndex][key] === value) {
result[explosionIndex] = json[explosionIndex];
}
}
return result;
}
(e.g. filterJSON(myjson, "data1", true) will give all explosions with data1:true)
This is not specific to d3.
Then you could use something like this for the d3-side of things:
explosions.data(myFilteredData).exit().remove(); // remove ones you don't want
explosions.enter().append("path")... // add back ones you do want
If I understand your application, it would actually be better to just toggle the visiblity attribute of the SVG elements.
var sliderrange = [20040101, 20040201]; //replace with code based on your slider
explosions.selectAll(".explosionpoint").attr("visibility", function(d) {
//Replace with the correct date comparison logic
return d.date < sliderrange[1] && d.date > sliderrange[0] ? "visible" : "hidden";
});
D3 does have a very natural way of doing this. I'll assume your data looks something like this:
[{name: explosion1name, day: 20040110,...}, {name: explosion2name, day: 20040111,...}]
...and that you've got some variable, we'll call it explosionsData, to reference the data.
You can then draw your explosions with a function that takes the values from your slider. See the .filter I've added below.
function drawExplosions(startDay, endDay) {
explosions.selectAll("path") //make a path and attach data
.data(collection.features)
.enter().append("path")
.filter( function (d) { return ( (d.day > startDay) && (d.day < endDay) )})
.attr("d", path)
.style("stroke","red") //color the path points
.style("stroke-width",2) //size of point stroke
.attr("class","explosionpoint")
.append("title") //title is the 'name' field in the json file
.text(function(d) { return d.properties.name; });
Just call this function whenever your slider values changes.