简体   繁体   English

在 Google 图表中居中对齐标题

[英]Center align title in Google Chart

How can I center align the chart title in a Google Charts chart?如何在 Google Charts 图表中居中对齐图表标题?

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.我要做的是从图表中删除标题并在图表上方添加一个标题,这样您就可以使用 CSS 将其居中。

Add header to page:将页眉添加到页面:

<h2 class="piechartheader">Pie Chart Header</h2>

To remove the title from the chart use titlePosition: 'none' .要从图表中删除标题,请使用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.您可以使用 X 的值(在我的示例中为 100)以将标题向左或向右拖动。

Having the same problem, together with variable chart title length for the same chart, the Tall Angel solution, although simple, wouldn't solve it.遇到同样的问题,加上同一图表的图表标题长度可变, Tall Angel解决方案虽然简单,但无法解决。

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).因此,同时考虑到Joe P 的回答,我创建了一个自动解决方案,该解决方案与google.visualization.LineChart的标题完全重叠(未使用其他类型的图表进行测试,但也可以使用)。

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: CSS:

.googleChartTitle {
    font: bold 11px Arial;
    text-align: center;
    position: absolute;
    width: 100%;
    padding-top: 8px;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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