Multiple Google Charts inside JQuery Cycle - javascript

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.

Related

Animate New data in Google line charts

I am making an line chart that will have lines appear and disappear with user interaction. Is there a way to animate the added data like the chart startup animation? Or fade line in and out so that it isn't so abrupt?
One Idea I had was to to set the new data to 0 then have have it animate to the new data but was wondering if there was another way.
Hope that makes sense
to animate from one data set to another, redraw the same chart with new data.
see following, working snippet. the data in each column is "swapped" before redraw...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([["PR","CE","PE"],["5500",1875,2025],["6000",61500,104775],["6100",450,13725],["6500",35400,421800],["6600",150,121950],["6700",600,770925],["6800",13650,370425],["6900",33375,586650],["7000",744375,1122075],["7100",229200,355875],["7200",199800,689850],["7300",461550,244425],["7400",442950,439125],["7500",835350,484725],["7600",459000,82800],["7700",482250,48000],["7800",893250,11550],["7900",1215600,13500],["8000",741150,93525],["8100",242325,6150],["8200",326175,1500],["8300",365850,75],["8500",104850,2925],["9000",13050,11775]]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
var options = {
animation: {
startup: true,
duration: 2000,
easing: 'linear'
}
};
var redrawTimes = 0;
google.visualization.events.addListener(chart,'animationfinish',function () {
for (var i = 0; i < data.getNumberOfRows(); i++) {
var swap1 = data.getValue(i, 2);
var swap2 = data.getValue(i, 1);
data.setValue(i, 1, swap1);
data.setValue(i, 2, swap2);
}
if (redrawTimes < 5) {
setTimeout(function () {
chart.draw(data, options);
redrawTimes++;
}, 2000);
}
});
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Just add data to your DataTable and the call .draw() on your chart again, using options which contains the animation settings.
Options could look like
var options = {
animation: {
duration: 600
}
};
And then just call chart.draw(DataTable, options) to animate it.
See example live at codepen. Just add data with the button and it'll smoothly be added to the line.

Google Charts Y-Axis unsorted

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

how to pass options to JavaScript in a cshtml page

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.

Create Bar Chart using JavaScript

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

Google Charts - animation transition example

Take a looka t my JS below, for my drawChart function for a google chart. This works as I expected. HOWEVER, because var chart ... is inside the drawChart function, the animations do not work - instead google thinks it's creating a brand new chart each time, and just refreshes the chart.
I would like to do something like in their examples, where the data moves according to my settings (1000ms, default easing: linear). Examples are here: https://developers.google.com/chart/interactive/docs/animation
If I pull out the var chart ... from the drawChart function, I get a "Chart not defined" error. Appreciate the help from anyone who has worked with google charts a lot. Thanks for the help.
var chart = "notSet";
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(setGoogleData);
google.setOnLoadCallback(drawChart);
newValue = 0;
var data = [];
function setGoogleData(){
data[0] = new google.visualization.DataTable(JSON_DATA_LOCATED_HERE);
data[1] = new google.visualization.DataTable(JSON_DATA_LOCATED_HERE);
var chart = new google.visualization.LineChart(document.getElementById('stopByTripChart'));
}
function drawChart() {
if(chart == "notSet"){
var chart = new google.visualization.LineChart(document.getElementById('stopByTripChart'));
}
var options = {"title":"Average Load Summary","titlePosition":"in","width":1100,"height":700,"hAxis.slantedTextAngle":90,"hAxis.position":"out","pointSize":5,"animation.duration":1000,"animation.easing":"linear","hAxis.showTextEvery":1,"hAxis.title":"Stops"};
chart.draw(data[newValue], options);
}
function changeChart(){
newValue = document.getElementById("chartNumber").value;
drawChart();
}
I've never tried Google charts myself, but I think such a code would work:
var chart = null;
function drawChart() {
if(chart === null){
chart = new google.visualization.LineChart(document.getElementById('stopByTripChart'));
}
var options = {"title":"Average Load Summary",
"titlePosition":"in",
"width":1100,
"height":700,
"hAxis" :{"slantedTextAngle":90,
"position":"out",
"showTextEvery":1,
"title":"Stops"},
"pointSize":5,
"animation":{"duration":1000,
"easing": 'out'};
chart.draw(data[newValue], options);
}
function changeChart(){
newValue = document.getElementById("chartNumber").value;
drawChart();
}
Otherwise, the error about chart not being defined might come from the fact that you might have placed your code before the load of the google library. Hence, chart was called before the google objects existed (tho it's hard to tell with just that snippet).

Categories

Resources