Google Line chart from CSV - javascript

I am quite new to java-script and html stuff.. I am trying to make a basic line chart with Google chart using example.csv file but something is wrong. I dont see any chart. Nothing is being displayed. Please help. I came up with code after reading some similar codes
All i need is to start with this basic working code and develop into more advanced shape
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="jquery.csv-0.71.js"></script>
<script type="text/javascript">
//google.load('visualization', '1', {packages: ['corechart', 'line']});
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(BasicLine);
function BasicLine() {
// grab the CSV
$.get("example.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
var data = new google.visualization.arrayToDataTable(arrayData);
]);
var options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Temperature'
},
backgroundColor: '#f1f8e9'
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
My CSV File is as below
Hour, Temperature
1, 70
2, 65
3, 60
4, 65
5, 67
6, 69

There is an syntax-error(the console should have told you about this).
Fixed version:
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(BasicLine);
function BasicLine() {
$.get("example.csv", function(csvString) {
var arrayData = $.csv.toArrays(csvString,
{onParseValue: $.csv.hooks.castToScalar}),
data = new google.visualization.arrayToDataTable(arrayData),
options = {
hAxis: {
title: 'Time'
},
vAxis: {
title: 'Temperature'
},
backgroundColor: '#f1f8e9'
},
chart = new google.visualization
.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
},
'text');
}
</script>

Related

Adding different links to each column (Google Charts)

I need to add different links which open another page to every column on a column chart.
Clicks to every different columns should open another window.
My current template only works if columns are seperate from each other, i want to have it works even columns are contiguous.
My current template is that:
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['bar']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['test', 'test', 'test', 'test', {
role: 'link'
}],
['test', 0.60, 0.62, 0.64, 'link'],
['test', 0.38, 0.53, 0.56, 'link'],
['test', 0.46800, 0.52100, 0.55500, 'link'],
['test', 0.43300, 0.49700, 0.53900, 'link']
]);
var options = {
title: 'test',
subtitle: 'test',
chartArea: {
width: '100%'
},
hAxis: {
title: 'test',
},
vAxis: {
title: 'test',
format: 'percent'
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
google.visualization.events.addListener(chart, 'select', function(e) {
var selection = chart.getSelection();
if (selection.length) {
var row = selection[0].row;
let link = data.getValue(row, 2);
window.open(link, '_blank');
}
});
chart.draw(data, google.charts.Bar.convertOptions(options));
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
</body>
</html>

Why doesn't my Google chart work on Safari?

I am trying to draw a chart on screen using Google charts. It works on every browser except for Safari. The following is the code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the bar chart package.
google.charts.load("current", {"packages":["corechart", "line"]});
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url: "/get-data-for-chart",
data: {"objectId": 807},
dataType: "json"
}).then(function(response) {
// Create our data table out of JSON data loaded from server.
rawData = response;
if (rawData.rows != null) rawData.rows = rawData.rows.map(row => ({ c: [{ v: new Date(row.c[0].v) }, row.c[1]] }));
var data = new google.visualization.DataTable(rawData);
// Instantiate and draw our chart, passing in some options.
var options = {
chart: {
title: "Title of the chart"
},
width: 900,
height: 500,
hAxis: {
title: "Time Axis",
format: "MM-dd",
gridlines: {count: 15}
},
vAxis: {
gridlines: {color: "none"},
minValue: 0,
format: "currency"
}
};
var date_formatter = new google.visualization.DateFormat({
pattern: "MMM dd, yyyy HH:mm"
});
date_formatter.format(data, 0);
var chart = new google.visualization.LineChart(document.getElementById("chart_div"));
chart.draw(data, options);
});
}
</script>
<!--Div that will hold the chart-->
<div id="chart_div"></div>
What actually happens on Safari is that the area for the chart loads, but with incorrect labels I guess. And the actual chart does not load at all. Moreover, there are no errors shown in the console, so I can't debug this in a usual way. As mentioned earlier, this works with all other browsers. Also for the record, the Safari is running on MacOS Mojave. Any help is greatly appreciated! Thanks.

Wrapping text of x-Axis Labels for Google Visualization Charts

I cannot seem to wrap my label for my column chart. I tried fiddling around with the options but it doesn't make any difference.
This is my current chart view, as you can see the label for column 2 has completely disappeared as the column 1 label has overlapped:
this is my Column Chart View:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1.1", { packages: ["bar"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Faculty Name', 'Book', 'Book Chapter', 'Journal Article', 'Conference'],
#Html.Raw(rows)]);
var options = {
title: '',
'width': 800,
'height': 500
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data1, options);
}
</script>
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
You can reduce the font size down to 11 to get the label to show...
var options = {
'title': '',
'width': 800,
'height': 500,
'hAxis': {'textStyle': {'fontSize': 11}}
};
To do so, you will need to convert your options...
chart.draw(data1, google.charts.Bar.convertOptions(options));
you may draw a classical ColumnChart (when it is an option):
google.load("visualization", "1.1", {
packages: ["corechart"]
});
google.load("visualization", "1.1", {
packages: ["corechart"]
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data1 = google.visualization.arrayToDataTable([
['Faculty Name', 'Book', 'Book Chapter', 'Journal Article', 'Conference'],
['Commerce, Law and Managment', 4, 9, 9, 1],
['foobar',2,2,2,3],
['Health Sciences', 0,2,3,1],
['Humanities', 0, 1, 1, 0],
['Science', 0, 0, 0, 1]
]);
var options = {
title: '',
'width': 800,
'height': 500,
vAxis: {
gridlines: {
count: 10
}
}
};
var chart = new google.visualization
.ColumnChart(document.getElementById('columnchart_material'));
chart.draw(data1, options);
}
<div id="columnchart_material" style="width: 800px; height: 500px;"></div>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>

Scatter google chart - string values in Y axis

Since yesterday i try to draw chart with google charts. I have one problem. I tried to put strings on Y-axis, and script doesn't display anything.
I tried to do this with code:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['scatter']});
google.setOnLoadCallback(drawChart);
function drawChart () {
var data = new google.visualization.DataTable();
data.addColumn('number', 'document');
data.addColumn('string', 'term');
data.addRows([
[1 , 'word1'] , [3 , 'word2']
]);
var options = {
width: 900,
height: 500,
chart: {
title: 'weight of terms'
},
axes: {
x: {
0: {side: 'bottom'}
}
}
};
var chart = new google.charts.Scatter(document.getElementById('scatter_top_x'));
chart.draw(data, google.charts.Scatter.convertOptions(options));
}
</script>
That gives me a result: http://darium.linuxpl.eu/chart/
The goal: I wanna draw sometnig like this-
https://www.imageupload.co.uk/images/2015/08/25/asd.png
Is there any way to draw what I want?
Data column(s) for axis #0 cannot be of type string
So you need to change the axis,
google.load('visualization', '1.1', {packages: ['scatter']});
google.setOnLoadCallback(drawChart);
function drawChart () {
var data = new google.visualization.DataTable();
data.addColumn('string', 'term');
data.addColumn('number', 'document');
data.addRows([
['word1', 1] , ['word2', 3]
]);
var options = {
width: 900,
height: 500,
chart: {
title: 'weight of terms'
},
axes: {
x: {
0: {side: 'bottom'}
}
}
};
var chart = new google.charts.Scatter(document.getElementById('scatter_top_x'));
chart.draw(data, google.charts.Scatter.convertOptions(options));
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="scatter_top_x"></div>

Google column chart bug with the drawing in Web app

In my web app there is a google chart that uses dataTable(jsonObject) to draw the graphs and I have bugged data. Here is my code of calling the function :
<script type="text/javascript" src="//www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['corechart']});
</script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawVisualization);
function drawVisualization() {
function drawChart() {
var myJson= $.ajax({
url: "loadGraph.php",
dataType:"json",
async: false
}).responseText;
var visualization = new google.visualization.DataTable(myJson);
var options = {
title: "MyTitle",
titleTextStyle: { fontSize: 16, bold: true },
chartArea: { left: 32, right: 0,left: 52, width: 460, height: 180 },
legend: { position: 'top' }
}
var chart = new google.visualization.ColumnChart(document.getElementById('chartDiv'));
chart.draw(visualization , options);
}
google.setOnLoadCallback(drawVisualization);
</script>
My graph was correctly drawed, but recently a bugs occured. Please help
Check my post on this matter : Google column chart visualization from json object bug in MVC 4 C#
There is a bug on this type of displaying the charts. The good part is that the solution is pretty slick. Replace the values for the chart with this regex ->
myJson = myJson.replace(/"v":"(\d+)"/g, '"v":$1');
This will fix the visualization ;] Hope this helps

Categories