在谷歌图表中居中对齐标题

14

如何在Google图表中居中对齐图表标题?

我没有看到任何定位标题的选项。

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

我以前从未使用过Google Charts API,它是否有任何.css文件?如果有的话,如果您提供您的html和css文件,也许我可以通过css帮助您设置标题对齐。 - Masoud Keshavarz
3个回答

17
我会做的是从图表中移除标题,并在图表上方添加一个标题,这样您就可以使用CSS将其居中。

在页面上添加标题:

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

要从图表中移除标题,请使用 titlePosition: 'none'

var options = {
  width: 1100,
  height: 600,
  titlePosition: 'none',
  legend: {
    position: "none"
  }
}

了解更多信息:Google 图表文档 - 配置选项


2
同意,没有其他选项可以居中标题。你只能删除它。从图表中删除标题的简单方法是从选项中删除"title:"。 - Yevgeniy Afanasyev
1
在我的情况下,将titlePosition设置为“none”后,标题不会显示,并且顶部有很大的边距。是否有一种方法可以隐藏标题并让图表的其他组件自动填充此空间? - pkkoniec
2
第二个选项后缺少逗号。 - pkkoniec

2
我正在使用Google饼图。我搜索了标题所在的文本元素,并使用以下代码更改了其位置:
您可以像这样做:
最初的回答:
我正在使用谷歌饼图。我搜索了标题所在的文本元素,并使用以下代码更改了它的位置:
您可以尝试以下代码:
document.querySelector('#YourChartID > div > div:nth-child(1) > div > svg > g:nth-child(3) > text').setAttribute("x", 100);

您可以调整X的值(在我的示例中为100),以将标题向左或向右拖动。最初的回答。

1
有同样的问题,同时对于同一图表变量图表标题长度,Tall Angel的解决方案虽然简单,但并不能解决问题。因此,考虑到Joe P的答案,我创建了一个自动化解决方案,它与google.visualization.LineChart的标题完美重叠(尚未测试其他类型的图表,但也可以使用)。
代码:
    // 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);

CSS:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接