简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM