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);
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With