Center align title in Google Chart

2020-08-11 10:33发布

问题:

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

回答1:

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.



回答2:

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.