adding tooltips to google visualization bar chart - javascript

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/

Related

Highcharts Donut Chart customization

I'm working with highcharts and aiming to make a chart similar to this:
Now I've been playing around with the whole ordeal for a while now and I've come been able to reach the following point: http://jsfiddle.net/ccjSy/24/
$(function () {
$(document).ready(function () {
var chart = null;
var categories = ['Body Fat', 'Lean Mass'],
name = 'Body Fat vs. Lean Mass',
data = [{
y: 69,
color: '#F0CE0C',
drilldown: {
name: 'Body Fat',
color: '#F0CE0C'
}
}, {
y: 207,
color: '#23A303',
drilldown: {
name: 'Lean Mass' ,
color: '#23A303'
}
}];
// Build the data array
var browserData = [];
for (var i = 0; i < data.length; i++) {
// add browser data
browserData.push({
name: categories[i],
y: data[i].y,
color: data[i].color
});
}
// Create the chart
chart = new Highcharts.Chart({
chart: {
renderTo: 'donutchart',
type: 'pie',
spacingTop: 0
},
title: {
text: 'Your Body Fat vs Lean Mass',
style: {"color": '#7d7d7d'}
},
series: [{
name: 'Weight',
data: browserData,
dataLabels: {
style: {
fontFamily: 'ArialMT',
fontSize: '15px',
fontWeight: 'bold',
color: '#7d7d7d'
}
},
innerSize: '70%'
}],
tooltip: {
valueSuffix: ' lbs'
},
plotOptions: {
series: {
cursor: 'pointer'
}
}
});
});
});
I am thinking of leaving the space empty in the donut chart and inserting a custom circle with the Weight labeling.
However, I'm not certain how to tackle the following problems:
1) Leave more defined white spaces in between my two columns
2) How to properly align my two data labels? (As you can see in the model, they are in a straight line with neutral lines attached)
3) How to display the data underneath the two labels with both, the pounds and the percentage, as shown in the image.
Answering each of your three questions:
"More white space between columns?" -- add a plotOptions.pie.borderWidth element. The default value is 1. I used 5 to give it more white space.
"Properly align the two data labels?" -- You can compute a custom startAngle based on the two data values which will give you the correct angle to start with. Since you only have two data values in the series, that's easy.
Calculate startAngle for pie chart
var startAngle = 0 - (90 + (180 * (data[0].y / (data[0].y + data[1].y))));
Notice that if you change the y value for the first data object, the "Body Fat" portion of the pie chart will still maintain it's correct position, even as the portion of the chart grows larger or smaller.
"Display data underneath the two labels with custom formatting?" -- use plotOptions.pie.format to apply custom formatting to the pie value labels.
format: '<div style="position: relative; top: -20px; text-align: center">{point.name}<br><b><span style="font-size: 29px">{point.percentage:.0f}%</span></b> ({point.y} lbs)</div>'
Here's a working JSFiddle to see the results. You'll still need to add a dark gray circle behind the pie chart and add the "Total Weight" text but that shouldn't be too difficult.
Since I'm sure you'll be wondering about this, I should mention that there's a lot of white space under the pie chart title because it's leaving enough room for other labels that may appear above or below the pie. Since you're only using two values that will always be on the left/right sides of the pie chart, that doesn't change the fact that HighCharts is preparing to have other labels that may need to be displayed in the surrounding area.

How to hide tooltip title in google geocharts (and show other info in the tooltip)

Problem: if you enable the tooltips in google geocharts you cannot change the tooltip title, it's the first column you pass to the google chart draw method.
Instead of the CSS above to hide the title, you can set the showTitle option for the tooltip to false
tooltip: {
isHtml: true,
showTitle: false
}
Then you can use HTML markup in your tooltip to display the tooltip exactly the way you want.
In google geocharts if you enable the tooltip visualization, the title will be the first column of the data you passed to the google geochart.draw function.
In my case for performance consideration I found better to pass to google the ISO3166 nation 2 character code, it's resolved immediately, if you use the extended name it's not recognized immediately and it left some grey areas for some seconds.
Unfortunately after this choice, the tooltip title shows the 2 letter nation iso code, but I need to show another title.
I created a json array built this way:
var arCustomersDataByNation = [['Country', 'MyNumericData','Tooltip'],['RU',4,'My beautiful tooltip'],['AE',3,'NewTooltipTitle3'],['AF',1,'NewTooltipTitle4']...];
Added the data to a google dataTable :
var data = new google.visualization.DataTable();
data.addColumn('string', 'Country');
data.addColumn('number', 'MyNumericData');
data.addColumn({type:'string', role:'tooltip'});
for(var i = 1; i < arCustomersDataByNation.length; i++){
data.addRows([[arCustomersDataByNation[i][0],arCustomersDataByNation[i][1],arCustomersDataByNation[i][2]]]);
}
and defined the google chart options, the "isHtml: true" option is fundamental, is the only way to hack via CSS the geochart tooltip:
var arSubCColors = ['#ffffff','#99E6FF','#70DBFF','#1FC7FF','#00B4F1'];
var zoom_0_options = {
backgroundColor: {fill:'#f2f2f2',stroke:'#FFFFFF' ,strokeWidth:0 },
colorAxis: {minValue:0,maxValue:4,colors: arSubCColors},
datalessRegionColor: '#ccc',
displayMode: 'regions',
enableRegionInteractivity: 'true',
keepAspectRatio: true,
legend: 'none',
region:'world',
resolution: 'countries',
sizeAxis: {minValue: 1, maxValue:1,minSize:10, maxSize: 10},
tooltip : {textStyle: {color: '#666'}, showColorCode: true, isHtml: true}
};
Afyter this some CSS, the ".google-visualization-tooltip-item:first-child" rule hides the bold default title:
.google-visualization-tooltip{
border: 0px!important;
height : 30px!important;
list-style: none!important;
}
.google-visualization-tooltip-item
{
list-style: none!important;
position: relative;
top: -3px;
color: #707173!important;
font-weight: bold!important;
}
.google-visualization-tooltip-item-list .google-visualization-tooltip-item:first-child
{
display: none;
}
And here is the result:

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

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.

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.

Categories

Resources