Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 438
tafsir Avatar asked Aug 20 '14 07:08

tafsir


3 Answers

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;
}
like image 94
Bruno Silva Avatar answered Nov 02 '22 19:11

Bruno Silva


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.

like image 21
Joe P Avatar answered Nov 02 '22 19:11

Joe P


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.

like image 2
Tal Angel Avatar answered Nov 02 '22 19:11

Tal Angel