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
Related
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 making a google chart whith show and hide functionality.Means chart will be hidden on the page load and when user clicks a button chart will be made visible.
My code
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
function drawChart() {
var items = $(".label1").text();
var data = google.visualization.arrayToDataTable([
<%= chartItems %>
]);
var options = {
title: 'Poll Results'
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div" style="display:none; width:800px;height:500px;"></div>
My problem is that when user clicks on the button and chart is visible its not taking the full width and height(800x500).rather its taking an unknown dimension(400x200).
Note: when the chart is made visible in the page load itself, It works correctly.
Code is same change in HTML like this
<div id="chart_div" style=" width:800px;height:500px;"></div>
You can do as marios suggested and set dimensions inside that chart's options, but that won't fix all of the problems that come along with drawing a chart inside a hidden div. The Visualization APIs dimensional measurements don't work well inside hidden divs, so elements get positioned in the wrong place and have the wrong size in some browsers. You need to unhide the div immediately prior to drawing the chart, and you can hide it again when the chart is done drawing. Here's example code that does this:
var container = document.getElementById('chart_div');
container.style.display = 'block';
var chart = new google.visualization.PieChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
container.style.display = 'none';
});
chart.draw(data, options);
Use chartArea:{} to set width & height
function drawChart() {
var items = $(".label1").text();
var data = google.visualization.arrayToDataTable([
<%= chartItems %>
]);
var options = {
title: 'Poll Results',
chartArea: {
width: 800,
height: 500
}
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I confirm that this is a bug. It work if the div is hidden "visibility:hidden;"
It does not work if the CSS shows "display:none"
There is an option to ask for specific width and height the google chart api https://developers.google.com/chart/interactive/docs/customizing_charts?hl=es.
Directly give width in chart option.
For eg:
options='{
"width": "800"
}'
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.
I am using Jquery Flot to create a pie chart based on three different values, pause, nopause and sleeping. Initially it draws th pie chart correctly but after some redraw it gives me the following error.
Could not draw pie with labels contained inside canvas
My code is
Lecturer.socket.onmessage = function (message) {
var str = message.data;
var msg = str.split(":");
if(msg[0] == 'pause'){
var pause = parseInt(msg[1]);
var noPause = parseInt(msg[2]);
var sleeping = parseInt(msg[3]);
var data = [
{label: "Pause", data:pause},
{label: "No Pause", data:noPause},
{label: "Sleeping", data:sleeping}
];
var options = {
series: {
pie: {show: true}
},
legend: {
show: false
}
};
$.plot($("#pie-placeholder"), data, options);
}
};
HTML is
<div id="live-placeholder" class="flot"></div>
All the require js libraries are included. What I m doing wrong? Any Help ?
Thanks
You've got two problems:
1.) your placeholder div id doesn't match the $.plot call. live-placeholder != pie-placeholder.
2.) You don't need to calculate the percents yourself. Flot will do it internally.
See a working fiddle here.