I try to use Google Charts in one of my projects. Everything works pretty good, but my Y-Axis is completely unsorted.
This is the actual code I use to display my chart:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', { 'packages': ['corechart', 'bar'] });
google.charts.setOnLoadCallback(function () {
var title = 'Total Sales By Market and Year';
var subtitle = 'Cincinnati, Cleveland, Columbus, and Dayton';
var dataTable = new google.visualization.DataTable(
{"cols":[{"label":"UsageDates","type":"string"},{"label":"C1","type":"string"},{"label":"C2","type":"string"},{"label":"C3","type":"string"},{"label":"C4","type":"string"}],"rows":[{"c":[{"v":"14.06.2016"},{"v":0},{"v":0},{"v":6},{"v":7}]},{"c":[{"v":"15.06.2016"},{"v":50},{"v":0},{"v":0},{"v":0}]},{"c":[{"v":"16.06.2016"},{"v":0},{"v":13},{"v":1},{"v":3}]},{"c":[{"v":"20.06.2016"},{"v":5},{"v":7},{"v":0},{"v":0}]}]}
);
drawBarChart('chart_div', title, subtitle, dataTable);
//drawColumnChart('chart', title, dataTable);
});
function drawColumnChart(elementId, title, dataTable) {
var options = {
title: title,
vAxis: { format: 'decimal' }
};
var chart = new google.visualization.ColumnChart(document.getElementById(elementId));
chart.draw(dataTable, options);
}
</script>
The result looks a bit strange, I think the values for the Y-Axis aren't sorted but are taken as they come in.
I hope someone can help me out on this.
Try changing the cols definitions for C1..C4 from "string" to "number" to match the data you provided.
"cols":[{"label":"UsageDates","type":"string"},{"label":"C1","type":"number"},{"label":"C2","type":"number"},{"label":"C3","type":"number"},{"label":"C4","type":"number"}]
Codepen example
Related
The bulk of the examples I've found showing Google Charts have simple little arrays...
I need to pull an array from my server.
I can get a pie chart to draw, but it doesn't update.
Here is my attempt to get a flexible, redrawing pie chart:
At the top of my javascript, but before document.ready:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
My drawChart function:
function drawChart(arrFeedbackResult3) {
console.log('Draw a fucking chart ... ') + console.log(arrFeedbackResult3);
var chart_data = new google.visualization.DataTable(arrFeedbackResult3);
var options = {
title: 'Comments by Group',
sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
width: 400,
height: 400
};
chart = new
google.visualization.PieChart(document.getElementById('groupPieChartDiv'));
chart.draw(chart_data, options);
// chart = new google.visualization.PieChart(document.getElementById('groupPieChartDiv'));
// chart.draw(data, options);
}
And the function that, after a button is clicked, passes fresh data to drawChart:
function setupFeedback3(arrFeedbackResult3){ // Create Group summary Graphs
console.log('Groups summary from DB: ') + console.log(arrFeedbackResult3);
drawChart(arrFeedbackResult3);
} // END setupFeedback3
I get a "table has no columns" message on my page with the above code.
The array, arrFeedbackResult3, is formatted correctly and does render a chart when I change the code but end up without the ability to refresh.
Any help appreciated. I think I'm just missing the basic flow of using Google Charts...and how/where the callback should be used.
Updating with my next attempt after a very generous and detailed reply.
My js is in a separate file from the html. I cannot get the passing of an array via callback to work. I get "not a constructor" errors or "not a function." I think because adding a parenthetical value breaks the code.
I also don't understand the comment about document.ready in the answer...I have kept document.ready in order to load all my other functions.
Right after document.ready I have:
google.charts.load('current', {
packages:['corechart'],
callback: drawChart
});
Then, after my db POST to get data, I call:
function setupFeedback3(result){ // Create Group summary Graphs
arrFeedbackResult3 = result; //Store in global variable for access by chart
drawChart();
} // END setupFeedback3
arrFeedbackResult3 is a GLOBAL variable - only way I could get the data to the draw chart function.
Then:
function drawChart() {
console.log('Draw a chart ... ') + console.log(arrFeedbackResult3);
// var chart_data = new google.visualization.DataTable(arrFeedbackResult3);
var chart_data = google.visualization.arrayToDataTable(arrFeedbackResult3);
var options = {
title: 'Comments by Group',
sliceVisibilityThreshold: 1/20,
width: 400,
height: 400
};
var chart = new google.visualization.PieChart(document.getElementById('groupPieChartDiv'));
chart.draw(chart_data, options);
}
This is working, and the chart does update as you feed different data, but it seems a shoddy state of affairs. One specific example of passing data, vs. a stupid simple example or using AJAX inside the function, would have been really helpful.
first, recommend not using jsapi to load the library.
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.js from now on.
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only change the load statement...
google.charts.load('current', {packages:['corechart']});
next, the callback can be added to the load statement...
google.charts.load('current', {
packages:['corechart'],
callback: drawChart
});
or you can use the promise it returns...
google.charts.load('current', {
packages:['corechart']
}).then(drawChart);
also, the load statement will wait until the document is ready by default,
so it can be used in place of --> $(document).ready
finally, when creating a data table,
the argument for the constructor should be JSON, not a simple array
see Format of the Constructor's JavaScript Literal data Parameter,
for the specific JSON format
if you want to create a data table from a simple array,
use static method --> arrayToDataTable
recommend setup similar to following...
google.charts.load('current', {
packages:['corechart']
}).then(function () {
// get data
drawChart(arrayData);
});
function drawChart(arrayData) {
var chart_data = google.visualization.arrayToDataTable(arrayData);
var options = {
title: 'Comments by Group',
sliceVisibilityThreshold: 1/20,
width: 400,
height: 400
};
var chart = new google.visualization.PieChart(document.getElementById('groupPieChartDiv'));
chart.draw(chart_data, options);
}
function setupFeedback(arrayData) {
// get data
drawChart(arrayData);
}
UPDATE
you can use the promise the load statement returns as the callback and the document ready
just move the code as shown below...
then you can load your ajax call to get the data
google.charts.load('current', {
packages:['corechart']
}).then(function () {
// move code from document ready here
// get data
getData();
});
function getData() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: sourceURL,
success: setupFeedback
});
}
function setupFeedback(result) {
// you could draw the chart here
// just move the code from drawChart
// or pass the data along to another function
drawChart(result);
}
function drawChart(result) {
var chart_data = google.visualization.arrayToDataTable(result);
var options = {
title: 'Comments by Group',
sliceVisibilityThreshold: 1/20,
width: 400,
height: 400
};
var chart = new google.visualization.PieChart(document.getElementById('groupPieChartDiv'));
chart.draw(chart_data, options);
}
I have a page that displays data in a form of a Pie Chart. I use Google Charts and here is the code:
<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([
['Product', 'Sale In Percent'],
['product2', 5.5],
['product3', 7.5],
['product4', 1.5],
['product5', 8.5],
]);
var options = {
title: 'Product Sales'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart2'));
chart.draw(data, options);
}
</script>
<div id="piechart2" style="width: 700px; height: 400px; position: relative;"></div>
And here's a working JS FIDDLE:
https://jsfiddle.net/alex4uthis/j78vmq00/2/
Here I have 1 more product as product1 and its value is 77. Since this value is always higher I omitted from the chart. When I draw the chart we can see product2 percent become 23.9%, product3 percent become 32.6 etc.... But I want to get the pie chart draw with what I have given in 'Sale In Percent' column.(Means product1 draw with 5.5 etc...)
Please help me in this.
You can't have a pie chart that totals less than 100%, so the library is assuming the sum of the values you pass it is to be considered 100%.
Since you aren't passing the 77, your values only add up to 23. 5.5/23 = 23.9% and 7.5/23 = 32.6%
If you want to have the chart display with the labels reading your provided percentages, the first thing you need to do is set the pieSliceText option to value to label the slice with 'The quantitative value of the slice.' (https://developers.google.com/chart/interactive/docs/gallery/piechart?hl=en#configuration-options)
Next, if you want to show the label with a percent sign you will just want to go manually add them after the chart renders like so:
[].slice.call(document.querySelectorAll('#piechart2 path + text'))
.forEach(function(el) {
el.textContent += '%';
});
Here is a working fiddle: https://jsfiddle.net/tq37y0p5/1/
I would like to set the colors in a google chart from my code, and not sure how to do it. I have this in a cshtml page.
<script type="text/javascript">
// Load the Visualization API and the piechart package.
//google.load('visualization', '1.0', { 'packages': ['bar'] });
google.load('visualization', '1.0', { 'packages': ['corechart'] });
var visualization;
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawCharts);
function drawCharts() {
var titleName = "Rounding Eligible";
$("#chartHeader").html(titleName);
var options = {
'backgroundColor': 'transparent',
title: titleName,
subtitle: 'Range of ddd to ddd', seriesType: "bars",isStacked: true,
series: { 0:{color:"#009add"} ,1:{color:"#009844"} ,2: {color:"#ef7521"} ,3: {color:"#89d2e6"},4:{color:"#82bc00"},5:{color:"#f19f53"},6:{color:"#0055b7"},#(Model.NumSeries) : { type: "line", visibleInLegend: false, color: "#FF0000" }},
vAxis:{title: "Count", minValue:10}
};
// Create the data table.
var data = google.visualization.arrayToDataTable(#Html.Raw(Model.ChartJson));
var chart_div = document.getElementById('chartDiv');
var chart = new google.visualization.ComboChart(chart_div);
chart.draw(data, options);
//setup a temp image to gold hold the chart
createHiddenImage('hiddenCanvas1', 'chartDiv', chart.getImageURI());
}
</script>
What I would like to do is replace my colors ( 0:{color:"#009add"} ,1:{color:"#009844"}) to be based on something in the code and do something like
isStacked: true,
series:
#foreach seriesvalue in #Model.seriesValues
{#Html.Raw(seriesvalue);},
Axis:{title: "Count", minValue:10}
I have no idea what is possible to accomplish this, is it best to just pass the whole options object from the model? Basically I can't figure out how to do it.
Just use JSON serialization:
series: #Html.Raw(JsonConvert.SerializeObject(Model.seriesValues))
You'll want to make seriesValues a Dictionary keyed by the number you want associated with each color.
For a deeper dive, see this answer: Using Razor within JavaScript
You can access properties from your model anywhere on the page, including within the script, via:
#Model.MyPropertyName
With that in mind, your javascript can look something like this:
myColor = '#Model.MyGreenColorProperty';
Note the single quotations around the #Model... this is very important, and will not work if the value is not surrounded by the quotes.
I'm trying to create a Bar Chart using Google's jsapi, and I've downloaded the following code (with my own changes), that needs to create Bar Chart.
google.load("visualization", "1", {packages:["corechart"]});
drawChart(AvgTimeInConference, keysSorted3);
function drawChart(AvgTimeInConference, keysSorted3) {
var DataTable=[];
DataTable.push(['Conference', 'Average Duration']);
for (var i=0; i<keysSorted3.length; i++)
{
if(keysSorted3[i]!=="")
{
var x=[keysSorted3[i], AvgTimeInConference[keysSorted3[i]]];
DataTable.push(x);
}
}
var data = new google.visualization.arrayToDataTable(DataTable);
var options = {
title: 'average durations length of the conferences, grouped by Conference Type',
vAxis: {title: 'Average Duration', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
The code works greate, until it gets to the line "var data = new google.visualization.arrayToDataTable(DataTable);". Data Table at this point is an array that contains the data in cells (first cell - headers, second and on are the data according to headers). When trying to use that function, the run get stuck and doesn't move on. doe's anyone has an idea why it happens? is DataTable not in the right format? Thanks!
Edit: The DataTable object from debug
I am trying to create a cycle/slider that has two google charts in it. I can display them separately on the page with the below code, but when space became premium I decided to go to slider/cycle. With the below code. The first chart draws but when the second scrolls into view. There is no chart. It only says: Unable to get property 'length' of undefined or null reference on Chrome: Cannot read property 'length' of null. I realize that when one chart is visible the other is not. But my unfamiliarity with javascript is making it hard to come up with an answer that will turn display:'block' to display:'none at the appropriate times and back. Any help would be much appreciated.
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function drawCharts() {
var data1 = google.visualization.arrayToDataTable(<% =jsostring%>);
var options1 = {
title: 'PSNL Weight Chart',
backgroundColor: {fill:'none'}
};
var data2 = google.visualization.arrayToDataTable(<% =jsostring2%>);
var options2 = {
title: 'PSNL Sleep Chart',
backgroundColor: {fill:'none'}
};
var chartA = new google.visualization.LineChart(document.getElementById('chart_div'));
chartA.draw(data1, options1);
var chartB = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
chartB.draw(data2, options2);
}
google.setOnLoadCallback(drawCharts);
google.load("visualization", "1", { packages: ["corechart"] });
</script>
I guess the answer is very basic. I'm not a java person. I searched and thought about it. The answer, which I found on another site is:
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
function drawCharts() {
var data1 = google.visualization.arrayToDataTable(<% = jsostring%>);
var options1 = {
title: 'PSNL Weight Chart',
backgroundColor: {fill:'none'}
};
var data2 = google.visualization.arrayToDataTable(<% = jsostring2%>);
var options2 = {
title: 'PSNL Sleep Chart',
backgroundColor: {fill:'none'}
};
var chartA = new google.visualization.LineChart(document.getElementById('chart_div'));
document.getElementById('chart_div').style.display = 'block';
document.getElementById('chart_div2').style.display = 'none';
chartA.draw(data1, options1);
var chartB = new google.visualization.ColumnChart(document.getElementById('chart_div2'));
document.getElementById('chart_div2').style.display = 'block';
document.getElementById('chart_div').style.display = 'none';
chartB.draw(data2, options2);
}
google.setOnLoadCallback(drawCharts);
google.load("visualization", "1", { packages: ["corechart"] });
</script>
As the jquery scroll through. It will turn on the first Div_Chart and turn off the other before it scrolls into view.