Showing dates where there are no values in Google Charts - javascript

I've got the below script & it's working perfectly.
However, it may be the case that on some days there are no orders. In this case, the date should still show, but the value should be zero.
Like in the above, it jumps from 06-19 to 06-21.
Is there a way to still show 06-20 and just have the value as zero? The missing date doesn't exist in the database as a record is only created when an expense is submitted, so I'm a bit lost.
Thank you in advance
Head Script
<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 data = google.visualization.arrayToDataTable([
['Date', 'Total Orders'],
['2017-9-6',200],['2017-8-6',1500],['2017-7-7',800],['2017-7-3',1,800],['2017-7-2',200],['2017-6-13',10000],['2017-10-5',800],['2017-10-12',4,500],['',],
]);
var options = {
title: 'Orders Per Day'
};
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart"));
chart.draw(data, options);
}
</script>
Body Script
<h3>Column Chart</h3>
<div id="columnchart" style="width: 900px; height: 500px;"></div>

To address this issue you would need to define that your axes are continuous. This can be achieved by defining the data type for your chart columns.
Below is an example that uses different data to your problem to make it easier to see the solution. The string dates in the array need to be converted to a date object to meet the data type criteria. This is achieved by using the new Date() object.
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', 'Total Orders');
data.addRows([
[new Date('2017-9-6'),200],
[new Date('2017-7-7'),800],
[new Date('2017-7-3'),800],
[new Date('2017-7-2'),200],
[new Date('2017-6-13'),300]
]);
var options = {
title: 'Orders Per Day'
};
var chart = new
google.visualization.ColumnChart(document.getElementById('columnchart'));
chart.draw(data, options);
}
</script>

Related

Locale language for google charts not working

In my page I load the chart as described in the docs. It's a view in asp.net that renders the output. The view checks if a class called Avstemning is populated then puts strings from that class into the chart as data. But if I use Norwegian letters like ø,æ, å. The chart data can't read it even as I specify the language option to use. What is going on here?
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
#if (Model.Avstemning != null)
{
<script type="text/javascript">
google.charts
.load('current', { 'packages': ['corechart'], 'language':'no' });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Model.Avstemning.Tittel'],
['#Model.Avstemning.Option1', #Model.Avstemning.One],
['#Model.Avstemning.Option2', #Model.Avstemning.Two],
['#Model.Avstemning.Option3', #Model.Avstemning.Three]
]);
var options = {
title: '#Model.Avstemning.Tittel'};
var chart = new
google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
}
If I change the data variable to take hard coded options with norwegian letters it works. But that's not exactly ideal. Any ideas on how to solve this? Inject javascript from controller?
I solved the encoding issue by using Html.Raw(). Not recommended if these are later to be stored in db, but works for displaying the data as I intended:
var data = google.visualization.arrayToDataTable([
['Avstemning', '#Html.Raw(Model.Avstemning.Tittel)'],
['#Html.Raw(Model.Avstemning.Option1)', #Model.Avstemning.One],
['#Html.Raw(Model.Avstemning.Option2)', #Model.Avstemning.Two],
['#Html.Raw(Model.Avstemning.Option3)', #Model.Avstemning.Three]
]);
var options = {
title: '#Html.Raw(Model.Avstemning.Tittel)',
};

Google Charts using CSV Data: $.csv is undefined?

So I have a working google chart that uses a CSV file, parses the CSV data as a string into an array, and uses the array as the datatable.
I actually asked a question and answered it myself Here.
That link will show you a full chunk of code that I used in my full working website.
I intended to just pull the script from the test file and drop it into my website, but now that I've moved it over and included the scripts I needed, I'm getting an error as:
Type Error: $.csv is undefined
Here is the code where $.csv is being utilized (var arrayData), this is a function for drawing the chart
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="jquery.csv.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript"> // load the visualisation API
google.load('visualization', '1', { packages: ['corechart', 'controls'] });
</script>
<script type="text/javascript">
function drawVisualization() {
$.get("Thornton.M2.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);
// CAPACITY - En-route ATFM delay - YY - CHART
var crt_ertdlyYY = new google.visualization.ChartWrapper({
chartType: 'LineChart',
containerId: 'crt_ertdlyYY',
dataTable: data,
options:{
width: 450, height: 160,
title: 'EU-wide en-route ATFM delays (year to date)',
titleTextStyle : {color: 'grey', fontSize: 11},
}
});
crt_ertdlyYY.draw();
});
}
google.setOnLoadCallback(drawVisualization)
</script>
</head>
<body>
<div id="crt_ertdlyYY"></div>
</body>
This example works fully as you can see from the link I had posted before hand, if you wanted to test it. But now that I pull it into my main site the .csv calls do not recognize. I also have 2 other google charts on this page that still work properly so it's isolated to this issue. I'm very new to google charts and pretty confused here!

looping through a list obtained from python in google line chart api

I want to loop through a list send from python to javascript in google line chart api ???
<html>
<head>
<style type="text/css">
#linechart_material{
margin-left: 150px
}
</style>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.1', {packages: ['line']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'No. of Tweets');
data.addColumn('number', 'Good-Review');
data.addRows([
for (int i=1, i<={{f}}, i++)
{
[i, {{a.i}}],
}
]);
var options = {
chart: {
title: 'Sentiment Analysis',
subtitle: 'in Respective Negative and Positive Values'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('linechart_material'));
chart.draw(data, options);
}
</script>
<body>
<div id="linechart_material">
<br><br><br><br><br><br>
</div>
</body>
here {{a}} is a list obtained from python and {{f}} in total length of the list.
I dont know javascript, so how can each value in {{a}} will iterate , over in javascript , i used the for loop , but its not working , and it shows blank page
You need to let python output your list:
data.addRows([
{% for x in a %}
[{{forloop.counter}}, {{x}}],
{% endfor %}
]);
You also have an error in how you're initialising google charts:
<script src="https://www.gstatic.com/charts/loader.js"></script>
google.charts.load('current', {'packages':['line']});
google.charts.setOnLoadCallback(drawChart);

instead of ready data how can i read from csv?

i have this code and i want to change the static data with data from csv
the csv is look like:
GPA,Total Distance,id
3.27,22.0,20032202
2,64.0,20038107
2.81,10.0,20051566
2.33,66.5,20060382
i want to add the GPA in y axis
and total distance in the X axis
when i try to add code from d3 library it does not works
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'GPA');
data.addRows([
[0, 0],
[1, 10],
[2, 23],
[3, 17],
[4, 18],
]);
var options = {
hAxis: {
title: 'Total Distance'
},
vAxis: {
title: 'GPA'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
Here is the best answer I can come up with to help you.
In your question, you have to tackle different topics in javascript
get content of a local file in javascript
parse this content as a csv file (and make it a multidimensional array)
prepare the values to put in the chart
First, add the following two libraries : jQuery for the simplified ajax calls to the file and jquery-csv for an also simplified way to parse the content.
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
Then, you have to re-route the charts callback : you have to point to a function that get asynchronously the file content (getFileContent in the example below).
Only in case of success, you can format the csv data into array.
And only then, you can serve the data to the chart by passing your formatted and sorted array to your drawbasic method.
Finally, you end up with that script
<script type="text/javascript">
google.charts.load('current', {
packages: ['corechart', 'line']
});
google.charts.setOnLoadCallback(getFileContent);
function getFileContent() {
var filePath = 'file:///path/to/file.csv';
// 1. Get local file content asynchronously
$.get(filePath, {}, function (data) {
console.log(arguments);
var lines = $.csv.toArrays(data); // 2. Parse the csv as a multidimensional array
var header = lines.shift(); // 3. Remove the header of the file
// 4. Sort the lines by the second column
lines.sort(function (a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
});
// 5. Pass your lines to the draw method
drawBasic(lines);
}, 'text')
.fail(function () {
console.log(arguments);
})
;
}
function drawBasic(lines) {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'GPA');
for (i = 0; i < lines.length; i++) {
// 6. Don't forget to parse as float the numbers in the array, they are strings at this point
// You'll get a 'Type mismatch. Value 3,27 does not match type number' error if you don't
var xValue = parseFloat(lines[i][1]);
var yValue = parseFloat(lines[i][0]);
data.addRow([xValue, yValue]);
}
var options = {
hAxis: {
title: 'Total Distance'
},
vAxis: {
title: 'GPA'
}
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
Don't forget to change the filepath in getFileContent, preceded by file://
I give credit to the answers in SO that helped me create this answer:
Javascript - read local text file
How to sort 2 dimensional array by column value?
Side note
In different conditions, it's much more common if you get csv (or, better with Javascript, JSON) via an HTTP call when working with Javascript to display data.
Local file reading may be reserved for server-side processing, that make this content available through HTTP.

Google chart does not appear even if no error

Here is my code to create google chart from csv data. ANd also no error. But even chart does not appear.
Here is the documentation for which works: http://economistry.com/2013/07/easy-data-visualization-with-google-charts-and-a-csv/
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script src="http://jquery-csv.googlecode.com/files/jquery.csv-0.71.js"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
// grab the CSV
$.get("Chart1-data.csv", function(csvString) {
// transform the CSV string into a 2-dimensional array
var arrayData = $.csv.toArrays(csvString, {onParseValue: $.csv.hooks.castToScalar});
alert(arrayData);
// 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]);
// set chart options
var options = {
title: "A Chart from a CSV!",
hAxis: {title: data.getColumnLabel(0), minValue: data.getColumnRange(0).min, maxValue: data.getColumnRange(0).max},
vAxis: {title: data.getColumnLabel(1), minValue: data.getColumnRange(1).min, maxValue: data.getColumnRange(1).max},
legend: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
Chart1-data.csv
Category,
A,34
B,23
C,14
D,57
E,18
Other,5
Do I missing anything in the code?
Good news: Your Code is fine! Your CSV file is the bottleneck.
Column names can't be null, means Category, => Category,''
No additional line breaks between data rows, means
A,34
B,23
=>
A,34
B,23
Result:
Category,''
A,34
B,23
C,14
D,57
E,18
Other,5
That is all! :)
There doesn't seem any kind of problem with this Google chart code snippet.
Though in browser console there are some Uncaught JavaScript errors.
Most importantly there is
" Uncaught null "error which is in reference to blank space after "Category" so Category, ' ' should work fine

Categories

Resources