google visualization api pie chart percents wrong position - javascript

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

Related

How To Dynamically Truncate The Y-Axis Title On Chart Resize/Reflow In Highcharts

I have a Highcharts Chart in a resizable div. Is there any way to get the Y-Axis Title to be responsive?
Try out in this plunker: http://plnkr.co/edit/3DXRlGkBlGoRdwxjP1rG?p=preview
I have used these options, but the width (height when rotated) of the title seems to not change at all:
chart: {
reflow: true
},
yAxis: [{
title: {
text: "Really really long Y-Axis Title. aaaaaa aaaaaa aaaaaaa aaaaaa aaaaa",
style: {
width: "100%",
whiteSpace: "nowrap",
textOverflow: "ellipsis"
}
}
}]
};
You can use responsive.rules to set the text's width depending on a chart's height.
With the options like below, the width of the text will be 100% if the chart's height is below 300 and 400% otherwise.
yAxis: [{
title: {
text: "Really really long Y-Axis Labelllllllll. Really really long Y-Axis Labelllllllll. Really really long Y-Axis Labelllllllll",
style: {
width: "400%",
whiteSpace: "nowrap",
textOverflow: "ellipsis"
}
}
}],
responsive: {
rules: [{
condition: {
maxHeight: 300
},
chartOptions: {
yAxis: {
title: {
style: {
width: '100%'
}
}
}
}
}]
},
example: http://plnkr.co/edit/h852BIAdPo3lCIesFmBT?p=preview
Responsive rules were added in Highcharts 5, so if you want to use older version, #FlorianHeer answer does the work.
You can set the width of the text when you first load the chart, then set the width again on resize.
chart: {
events: {
load: function () {
this.yAxis.map((axis) => {
axis.update({
title: {
style: {
width: this.plotHeight
}
}
});
});
}
}
}
plotHeight is the height of the chart plotting area, which I used for the maximum width of the axis title.
If you're using version 5.0.7+, you can maybe use the render event, which fires on chart load and on each redraw. I'm still on version 4.x so I had to use the load event with another event of my own (in my case, an event triggered by a jQuery click)
if you need the ellipses, you can extend Highcharts with a plugin to update the text value after the title has been rendered by hooking into the buildText function on the SvgRenderer prototype:
(function (H) {
H.wrap(H.SVGRenderer.prototype, 'buildText', customBuildTextFunc);
function customBuildTextFunc(proceed, wrapper) {
// original function
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
var yAxisClass = 'highcharts-yaxis-title';
var isYAxisTitle = wrapper.textStr
&& wrapper.element
&& wrapper.element.classList
&& wrapper.element.classList[0] === yAxisClass;
if (isYAxisTitle) {
var $container = $('<div></div>').append(wrapper.element.innerHTML);
var $tspans = $container.find('tspan');
var $first = $tspans.eq(0);
$first.append('...');
$container.empty().append($first);
wrapper.element.innerHTML = $container.html();
}
}
}(Highcharts));
I had issues with getSVG() when I used proper ellipses (…), so I just used three full stops (my ellipses were rendered as a box .. wrong encoding or something, I guess).
I'd say that is a bit of a strange behaviour, I would expect all parts to be reevaluated. But as the resulting Graph is an SVG, I guess some elements are forgotten in a reflow.
You could force a complete recalculation of spaces and sizes after resizing your containing div:
$("#outer").height(498).width(498);
c0.yAxis[0].setTitle({
text: 'Really really long Y-Axis Labelllllllll. Really really long Y-Axis Labelllllllll. Really really long Y-Axis Labelllllllll',
style: {
width: $('#outer').height()-100,
whiteSpace: "nowrap",
textOverflow: "ellipsis"
}}, true);
c0.reflow();

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/

Center align title in Google Chart

How can I center align the chart title in a Google Charts chart?
I don't see any options for positioning the title.
var data = google.visualization.arrayToDataTable([
["Period", "Daily"],
['a', 3],
['b', 3],
['c', 1]
]);
var options = {
title:"number of publications",
titleFontSize:30,
width: 1100, height: 600,
legend: { position: "none" }
}
// Create and draw the visualization.
new google.visualization.LineChart(document.getElementById("daily")).
draw(data, options);
What I would do is remove the title from the chart and add a header above the chart which would allow you to center it using CSS.
Add header to page:
<h2 class="piechartheader">Pie Chart Header</h2>
To remove the title from the chart use titlePosition: 'none'.
var options = {
width: 1100,
height: 600,
titlePosition: 'none',
legend: {
position: "none"
}
}
For more info: Google Chart Documentation - Configuration Options.
I am using Google pie chart. I searched for the text element where the title sits and changed its position using the following code:
You can do something like this:
document.querySelector('#YourChartID > div > div:nth-child(1) > div > svg > g:nth-child(3) > text').setAttribute("x", 100);
You can play with the value of X (100 in my example) in order to drag the title to the left or to the right.
Having the same problem, together with variable chart title length for the same chart, the Tall Angel solution, although simple, wouldn't solve it.
So, also considering the Joe P answer, I've created an automatic solution that overlaps perfectly with the title from google.visualization.LineChart (not tested with other types of charts, but could also work).
The code:
// Insert your chart code here...
const chart = new google.visualization.LineChart(dataDivElement);
chart.draw(dataTable, options); // Drawing chart
// After chart is drawn, add chart title
const node = document.createElement('div');
node.className = 'googleChartTitle';
node.innerHTML = 'Chart Title';
// Insert the node inside the chart divs
dataDivElement.childNodes[0].childNodes[0].append(node);
The CSS:
.googleChartTitle {
font: bold 11px Arial;
text-align: center;
position: absolute;
width: 100%;
padding-top: 8px;
}

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 Piechart: How to show values instead of percentage?

Is it possible to show values instead of percentage in Google Chart PieChart slices?
Thanks,
Yes. you can. Just set pieSliceText in the options like this
var options = {
width: 450,
height: 300,
title: 'My Daily Activities',
pieSliceText: 'value'
};​
Documentation: http://code.google.com/apis/chart/interactive/docs/gallery/piechart.html#Example

Categories

Resources