Google chart is not taking full width while jquery show and hide - javascript

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"
}'

Related

Google Pie chart percentage calculation

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/

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

Remove padding or margins from Google Charts

// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
var myData = {
'Mushrooms': 3,
'Onions': 1,
'Olives': 1,
'Zucchini': 1,
'Pepperoni': 2
};
var rows = [];
for (element in myData) {
rows.push([element + " (" + myData[element] + ")", myData[element]])
}
data.addRows(rows);
// Set chart options
var options = {'title':'How Much Pizza I Ate Last Night',
'width':450,
'height':300};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="chart_div"></div>
Example fiddle
How do I remove padding or margins in this example?
By adding and tuning some configuration options listed in the API documentation, you can create a lot of different styles. For instance, here is a version that removes most of the extra blank space by setting the chartArea.width to 100% and chartArea.height to 80% and moving the legend.position to bottom:
// Set chart options
var options = {'title': 'How Much Pizza I Ate Last Night',
'width': 350,
'height': 400,
'chartArea': {'width': '100%', 'height': '80%'},
'legend': {'position': 'bottom'}
};
If you want to tune it more, try changing these values or using other properties from the link above.
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
I arrived here like most people with this same issue, and left shocked that none of the answer even remotely worked.
For anyone interested, here is the actual solution:
... //rest of options
width: '100%',
height: '350',
chartArea:{
left:5,
top: 20,
width: '100%',
height: '350',
}
... //rest of options
The key here has nothing to do with the "left" or "top" values. But rather that the:
Dimensions of both the chart and chart-area are SET and set to the SAME VALUE
As an amendment to my answer. The above will indeed solve the "excessive" padding/margin/whitespace problem. However, if you wish to include axes labels and/or a legend you will need to reduce the height & width of the chart area so something slightly below the outer width/height. This will "tell" the chart API that there is sufficient room to display these properties. Otherwise it will happily exclude them.
It's missing in the docs (I'm using version 43), but you can actually use the right and bottom property of the chart area:
var options = {
chartArea:{
left:10,
right:10, // !!! works !!!
bottom:20, // !!! works !!!
top:20,
width:"100%",
height:"100%"
}
};
So it's possible to use full responsive width & height and prevent any axis labels or legends from being cropped.
There's a theme available specifically for this
options: {
theme: 'maximized'
}
from the Google chart docs:
Currently only one theme is available:
'maximized' - Maximizes the area of the chart, and draws the legend and all of the labels inside the chart area. Sets the following options:
chartArea: {width: '100%', height: '100%'},
legend: {position: 'in'},
titlePosition: 'in', axisTitlesPosition: 'in',
hAxis: {textPosition: 'in'}, vAxis: {textPosition: 'in'}
There is this possibility like Aman Virk mentioned:
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
But keep in mind that the padding and margin aren't there to bother you.
If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.
If you take away that margin then you will end up showing only a part of the labels or no labels at all.
So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.

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).

Google chart redraw/scale on window resize

How do I redraw/rescale a google linechart on window resize?
To redraw only when the window resize is completed and avoid multiple triggers, I think is better create an event:
//create trigger to resizeEnd event
$(window).resize(function() {
if(this.resizeTO) clearTimeout(this.resizeTO);
this.resizeTO = setTimeout(function() {
$(this).trigger('resizeEnd');
}, 500);
});
//redraw graph when window resize is completed
$(window).on('resizeEnd', function() {
drawChart(data);
});
The original code by Google simply does this at the end:
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
Changing it with a little javascript you can scale it when the window resizes:
function resize () {
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
window.onload = resize;
window.onresize = resize;
Since the window.resize event fires multiple times on each resize event, I believe that the best solution is to use smartresize.js and use smartdraw(). This limits the number of chart redraw’s per window.resize.
By using the provided js you can do it as simply as this:
// Instantiate and draw our user charts, passing in some options (as you probably were doing it)
var chart = new google.visualization.LineChart(document.getElementById('div_chart'));
chart.draw(data, options);
// And then:
$(window).smartresize(function () {
chart.draw(data, options);
});
This is the simplest way I can work out of doing this without causing too much stress to the browser:
var chart1 = "done";
$(window).resize(function() {
if(chart1=="done"){
chart1 = "waiting";
setTimeout(function(){drawChart();chart1 = "done"},1000);
}
});
All it does is wait 1 second before the chart reloads and doesn't let the function call again in this waiting period. as window resize functions are called multiple times any time you change the window size this helps make the function only actually work once each time you change the window size, the rest of the calls get stopped by the if statement.
I hope this helps
There is no option in Google Visualization API to make Google Charts responsive.
But we can make Google Charts responsive as Window Resizes. To make Google Chart responsive there is jQuery library available at GitHub - jquery-smartresize licensed under MIT License, which has the ability to resize graphs on window resize event.
This project on GitHub has two script files :-
jquery.debouncedresize.js: adds a special event that fires once after the window
has been resized.
&
jquery.throttledresize.js: adds a special event that fires at a reduced rate (no
more double events from Chrome and Safari).
Here are two examples of responsive charts...
Responsive Google Pie Chart
Responsive Google Bar Chart
We can change the bottom padding of visualization_wrap to match the desired aspect ratio of chart.
Calculate as Height / Width x 100
For a 16x9 display it would be 9/16 = 0.5625 x 100 = 56.25%
For a square it'd be 100%
We can customize chartarea option of Google Chart to ensure that labels don't get cut off on resizing.
Redraw/rescale a Google linechart on window resize:
$(document).ready(function () {
$(window).resize(function(){
drawChart();
});
});
I personally prefer the following approach, if You can live with using addEventListener, and don't mind lack of support for IE < 9.
var windowResizeTimer;
window.addEventListener('resize', function(e){
clearTimeout(windowResizeTimer);
windowResizeTimer = setTimeout(function(){
chart.draw(data, options);
}, 750);
});
Note the use of the setTimeout() and clearTimeout() functions and the added delay of 750 milliseconds, which makes this slightly less intensive when multiple resize events fire in quick succession (which is often the case for browsers on desktop when resizing using a mouse).
I've been stuck on the same thing for days and I found out that adding an event works best.
window.addEventListener("resize", drawChart);
Just add this line after declaring your function and it will work fine.
Replace drawChart with the name of your function.
Try with these approaches
window.dispatchEvent(new Event('resize'))
Chartkick.charts["<id of chart element like chart-1>"].redraw()
Using Tiago Castro's answer, I have implemented a line chart to show the demonstration.
google.load('visualization', '1', {
packages: ['corechart', 'line']
});
google.setOnLoadCallback(drawBackgroundColor);
function drawBackgroundColor() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'X');
data.addColumn('number', 'Compute Time');
data.addColumn('number', 'Compute Times');
console.log("--");
data.addRows([
[0, 0, 0],
[10, 10, 15],
[20, 20, 65]
]);
console.log(data);
var options = {
height: 350,
legend: {
position: 'bottom'
},
hAxis: {
title: 'Nb Curves'
},
vAxis: {
title: 'Time (ms)'
},
backgroundColor: '#f1f8e9'
};
function resize() {
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
window.onload = resize();
window.onresize = resize;
}
<script src='https://www.google.com/jsapi'></script>
<div id="chart_div">

Categories

Resources