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;
}
Related
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.)
I have kendo-chart at my js code.
By default, the legend area layout is that, there is list of colors, and the right of every color - there is label with series name. I want to reverse the order: put label first, and color second, and align it to right.
I think the best way to do it is by legend.item, but I don't know how to do it.
see the current state:
and here is demo of what I want will be:
You can create a custom legend visual using the Kendo legend methods.
legend: {
item: {
visual: function (e) {
// get the default color for the legend shape
var color = e.options.markers.background;
// get the default color for the legend text
var labelColor = e.options.labels.color;
// bounds of the legend
var rect = new kendo.geometry.Rect([0, 0], [100, 50]);
var layout = new kendo.drawing.Layout(rect, {
spacing: 5,
alignItems: "center"
});
// Recreate the legend shape (can be any shape)
var marker = new kendo.drawing.Path({
fill: {
color: color
}
}).moveTo(10, 0).lineTo(15, 10).lineTo(5, 10).close();
// recreate the label text
var label = new kendo.drawing.Text(e.series.name, [0, 0], {
fill: {
color: labelColor
}
});
// This is the key part: it draws the label first then the shape
layout.append(label, marker);
layout.reflow()
return layout;
}
}
The important part of this code is this part:
layout.append(label, marker);
Because we're specifying the label first, then the marker, the label should appear first.
I don't have a jsFiddle setup for this, but Kendo has an example in their dojo: http://dojo.telerik.com/OdiNi
In this case you'll have hide the legend.
legend: {
visible: false
},
And create your own legend in html.
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/
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:
// 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.