how to pass options to JavaScript in a cshtml page - javascript

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.

Related

How do you get a Google Chart to redraw based on data you pass to it?

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);
}

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

Interpolating in Google chart

I have the following code:
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create our data table out of JSON data loaded from server.
// var data = new google.visualization.DataTable('<>');
var data = google.visualization.arrayToDataTable([['Generation', 'Descendants'],[0,300], [85,300],[125,0] ]);
var options = {
title: 'Derating chart',
// Draw a trendline for data series 0.
lineWidth: 2,
hAxis: {title: 'Temperature [°C]', titleTextStyle: {color: 'black'}, logScale: false},
vAxis: {
title: "Irms [A]",
maxValue:8
},
pointSize:5
};
// Instantiate and draw our chart, passing in some options.
// Do not forget to check your div ID
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
It's quite simple, but I have the following problem:
- In my chart I have 3 points, is it possible to interpolate the values between that points? I need to display the values between them when you put the mouse over the line
There should be an option for this... but checking forums and documentation have found none. Closest to this is using a trendline, but values don´t match your line. So your only way is doing something manually. Here is a workaround I made using jquery :
//you need to have in options tooltip:{isHtml:true} for this to work
google.visualization.events.addListener(chart, 'ready', function(){
$('#chart_div svg path').mousemove(function(e){
$('.google-visualization-tooltip').remove(); // remove previous tooltips
var x=e.offsetX; // get x coordinate
var y=e.offsetY; //get y coordinate
var xValue= Math.round(chart.getChartLayoutInterface().getHAxisValue(x)); // get chart x value at coordinate
var yValue=Math.round( chart.getChartLayoutInterface().getVAxisValue(y)); // get chart y value at coordinate
// create tooltip
var tootlip = $('<div class= "google-visualization-tooltip"><ul class="google-visualization-tooltip-item-list"><li class="google-visualization-tooltip-item"><span >X : '+xValue+'</span></li><li class="google-visualization-tooltip-item"><span>Y : '+yValue+'</span></li></ul></div>');
tootlip.css({position:'absolute', left:(x+20)+'px', top:(y-100)+'px', width:'100px', height:'70px'}) // set tooltip position
$('#chart_div').append(tootlip); // add tooltip to chart
})
$('#chart_div svg path').mouseout(function(e){
$('.google-visualization-tooltip').remove();
})
})
Full fiddle: http://jsfiddle.net/juvian/48ouLbmm/
Note: without the mouseout it works better, but tooltip stays until next mouseover

Organizing graph options in Google Charts

I'm creating a handful of pie charts using Google Charts. The majority of the graph options for the charts I'm creating are the same, except the titles. Is it possible to maintain a default set of options but write certain specific options for each graph (in this case, I just need to set a title).
Here's an example of the code I'm using:
var graphOptions = {
is3D: true,
pieSliceText: 'label',
colors: ['#F9B641', '#FBCB75', '#FCE1B0', '#FFF8EB', '#FFFFFF'],
backgroundColor: 'transparent',
titleTextStyle: {
color: '#FFF'
},
legend: {
textStyle: {
color: '#FFF'
}
},
chartArea: {
width: '90%',
height: '80%'
}
};
function pieChart1() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 216],
['Female', 238]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart1'));
chart.draw(data, graphOptions);
}
function pieChart2() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Gender', 'Number'],
['Male', 116],
['Female', 98]
]);
// Create and draw the visualization.
var chart = new google.visualization.PieChart(document.getElementById('pieChart2'));
chart.draw(data, graphOptions);
}
How would I go about setting the title option for each graph while still pulling the options from graphOptions?
As David explained, you can create an options object, and then edit properties of that object individually.
Here is a jsfiddle that shows it in action.
Note: you cannot see the titles because the BG and font color is white. Just do a ctrl+a to select everything and see them hidden there
Basically, you create a variable both functions can access (in your case graphOptions). In each function you set a new variable called options to equal graphOptions. You can then change the title property of the options variable to whatever you want without changing your default options template graphOptions, and use the options variable to draw the graph.
For your code, that means adding this code to each function:
var options = graphOptions;
options.title = "Pie Chart X"
You can change the title to whatever is appropriate, different for each graph. Then in the graph draw command, you change graphOptions to options to get
chart.draw(data, options);
Normally you'd do:
var options = { title: 'My Chat Title' };
In your case add title to your graphOptions object then do:
graphOptions.title = "The New Title";
for each graph.

How to set images as legends in Google Charts

I am trying to use images as legend in Google Charts. This is how it currently looks like:
And this is how it should look like:
This is my JavaScript code to draw the chart:
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Champions', 'Games', 'Wins', 'Loses'],
['Ezreal', 21830, 12172, 9658],
['Taric', 17835, 9658, 8177],
['Graves', 13567, 6558, 7009],
['Lee Sin', 12738, 6349, 6389],
['Blitzcrank', 11965, 6132, 5833],
['Nunu', 10946, 5407, 5539],
['Sona', 9660, 5226, 4434],
['Corki', 9457, 4389, 5068],
['Jax', 8669, 4358, 4311],
['Amumu', 8396, 4743, 3653]
]);
var options = {
title: 'Most played',
backgroundColor: '#EEEEEE',
hAxis: {title: 'Champions', titleTextStyle: {color: 'red'}}
};
var chart = new google.visualization.ColumnChart(document.getElementById('most-popular'));
chart.draw(data, options);
}
I already tried to embed the <img> tags into the array like this:
['<img src="img/ezreal.png">'Ezreal', 21830, 12172, 9658]
Unfortunately, Google Charts does some kind of escape that string so that the whole HTML code is shown.
So I am looking for a way to include those images with Google Charts. If that is not possible I am looking for other JavaScript libraries which could do the job.
it is not possible! ( short answer, on mobile)

Categories

Resources