Remove padding or margins from Google Charts - javascript

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

Related

google visualization api pie chart percents wrong position

I'm stuck at google visualization api pie chart. Percent labels are mis-aligned a bit
Here is options
coreData = {
options: {
width: '550',
height: '400',
chartArea: {
height: "90%",
width: "90%"
},
}
};
And here is result :
As You can see there is 62 number sliced (62.7 should be)
How do i place them correct?
Also I'm using bootstrap3 and inspected css, everything seems correct and no overrides here
The draw() method should be called after the chart container is already visible(no 'hidden' class etc.)

adding tooltips to google visualization bar chart

I'm trying to add custom tooltips to a Google Bar Chart, but I can't figure out how to do this.
Google provides a nice tutorial (at https://developers.google.com/chart/interactive/docs/customizing_tooltip_content), but it only discusses ColumnCharts, rather than Bar Charts.
Here's what my code looks like:
<div id="top_x_div" style="width: 900px; height: 500px;"></div>
google.load("visualization", "1.1",{packages:["bar"]});
google.setOnLoadCallback(drawStuff0);
function drawStuff0() {
var data = new google.visualization.arrayToDataTable([$data]);
var options = {
title: 'Categories',
width: 900,
legend: { position: 'none' },
chart: { title: 'popularity by number of queries',
subtitle: 'Number of times a category was queried' },
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
x: {
0: { side: 'top', label: 'Number of times a category was queried'} // Top x-axis.
}
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div0'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
$data is simply a PHP variable containing the rows of the chart.
Could someone explain how to add a custom tooltip to this chart?
I've looked all over the web for a solution, I haven't been able to find one...
Add a new column to the DataTable object with the role tooltip :
data.addColumn({type: 'string', role: 'tooltip'});
Then loop through data and add whatever tooltip you want (example from the one column bar chart fiddle below) for each row :
for (var i=0; i<data.getNumberOfRows(); i++) {
data.setValue(i, 2, 'Tooltip #'+i);
}
demo -> http://jsfiddle.net/pc3zmb8w/
I cannot guide you more exactly since we dont know what your PHP $data is or how your chart looks like. But this is basically how you should do it, in all cases, when you want to add custom tooltips to a chart dynamically ...
Update - styling the tooltip
As for "is there a way to have the tool-tips appear as a rectangle, rather than a speech blurb", in the options - set tooltip as isHtml :
var options = {
tooltip: {isHtml: true}
}
Then the tooltip appears as a rectangle like normal HTML-element tooltips. You can also specify that you want to use HTML inside the tooltip itself :
data.addColumn({type: 'string', role: 'tooltip', p: {'html': true}});
For example to show the tooltip with the colors of a normal tooltip, but using a larger fontsize and a certain font :
div.tooltip {
background-color: #ffffca;
color: #000023;
padding: 10px;
font-size: 20px;
font-family : 'arial';
}
Set the tooltip as in original answer :
data.setValue(i, 2, '<div class="tooltip">Tooltip #'+i+'</div>');
demo -> http://jsfiddle.net/yhhhcj2f/

google bar/column chart set proper label width and chartarea width

i am using google chart to render charts, but sometimes the label is too long that the chart gets chopped, sometimes the chart is so long that the label gets cutting off, please check jsfiddle to see.
google.load('visualization', '1', {packages: ['corechart']});
var graphTitle = '', dataPoints = [];
function drawVisualization() {
// Create and populate the data table.
var data = google.visualization.arrayToDataTable([
['Option', 'Percent'],
['More than 75%', 47],
['50% to 74%', 36],
['30% to 49%', 10],
['10% to 29%', 4],
['Less than 10%', 3]
]);
$('body').data('quickpoll_179', data);
// Create and draw the visualization.
new google.visualization.BarChart(document.getElementById('quickpollChart')).
draw(data, {
title:'',
titleTextStyle: {color: '#000000'},
width:640, height:340,
legend: {position:'none'},
vAxis: {title: ""},
hAxis: {title: "",format:"#'%'"},
colors: ['#74317D'],
chartArea: {left:80.6,top:20, width:539.4,height:"340px"}
});
}
google.setOnLoadCallback(drawVisualization);
my question is how can i calc the proper width so if the chart is large, i can increase the whole container size and stop chart and lable being cutting off. i know for this case, i can increase the chart area, but it may not be applicable in every curcumstances. so it is better that i know how much space the google chart will take so i can dymaically resize the width and height of the container
I would say just decrease the size of the font, This is the default behaviour for a Google chart you cannot work with everything, what if the label was 1000 characters long. Then you would want the ellipse, you can still hover over the label to see the full text.
See updated fiddle: http://jsfiddle.net/9J4sS/1/
I achieved this by lowering the size of the text.
vAxis: {
title: "",
textStyle: {
fontSize:8
}
}
Or alternatively display your labels inside your graph using. http://jsfiddle.net/9J4sS/2/
vAxis: {
title: "",
textPosition: "in"
}

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.

Google chart: how to make right side of the "white space" empty?

I use Google Chart in order to build some graphichs together with text description.
On the first iteration I used small "title" for each graph type and that was looking well. But at some point I've added total value for each graph... and text started to be wrapped.
Question 1: Is there any way to prevent text wrapping (see the right portion of the chart)?
I've tried put text inside of "..." but Google chart just convert these tags into pure text.
Question 2: Is there any way to move whole graph to the left and consume unused area so the right part will have more space for text?
Any thoughts are welcome! Probably there is any other solution that will work for me?
P.S.
Please see how that looks right now on the screenshot:
P.P.S Here is JS code I use to display the graphs
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/google/jsapi.js"></script>
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawChart);
var expArray = [<%=ExperienceArray %>];
function drawChart() {
if (expArray.length > 0) {
$('#chart_div').show();
$('#MessagesDiv').hide();
var total = 0, train = 0, match = 0, ageing = 0;
for (var i = 0; i < expArray.length; i++) {
total += expArray[i][1];
train += expArray[i][2];
match += expArray[i][3];
ageing += expArray[i][4];
}
var data = google.visualization.arrayToDataTable([
['№', 'Total (' + total + ')', 'Training (' + train + ')', 'Matches (' + match + ')', 'Ageing (' + ageing + ')']
].concat(expArray));
var options = {
title: 'Gained experience',
allowHtml: 'true',
hAxis: { title: '', titleTextStyle: { color: 'black' } },
colors: ['#00FF00', '#6600CC', '#0000CC', '#000000']
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
} else {
$('#chart_div').hide();
alert("Data are absent");
}
}
</script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
Add the following code (adjust as necessary) to your options: chartArea: {left: 0}
So your options file would become this:
var options = {
title: 'Gained experience',
allowHtml: 'true',
hAxis: { title: '', titleTextStyle: { color: 'black' } },
colors: ['#00FF00', '#6600CC', '#0000CC', '#000000'],
chartArea: {left: 0}
};
Note: the current setting will slice off the entire axis labels, so you want to use something appropriate in size bigger than 0 (you can calculate something with an algorithm, or just fiddle until you have it like you want it).
For the legend, however, there is no trick.
When Google creates the SVG for the chart, it will split the legend in to two lines (two separate SVG text elements) so it's not easy to tweak. You can't very well fix it easily. One option is to create a separate chart with just the legend (and no chart area) which will mimic the legend, and then link the two charts together (if you want click interactivity with the legend).
Alternatively, you can reduce the font size using legend: {textStyle: {fontSize: 8}} or whatever font size will prevent the text from wrapping (again, you can create an algorithm or fiddle with it until it works).
As a separate option, you can create a manual legend and use javascript to mimic click interactivity, and then you can use CSS/Javascript to format it however you want.

Categories

Resources