在Google Chart中居中对齐标题

时间:2014-08-20 07:04:11

标签: javascript html charts

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

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

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

3 个答案:

答案 0 :(得分:10)

我要做的是从图表中删除标题,并在图表上方添加一个标题,以便您使用CSS将其居中。

向页面添加标题:

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

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

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

更多信息:Google Chart Documentation - Configuration Options

答案 1 :(得分:1)

我正在使用Google饼图。我搜索了标题所在的文本元素,并使用以下代码更改了其位置:

您可以执行以下操作:

document.querySelector('#YourChartID > div > div:nth-child(1) > div > svg > g:nth-child(3) > text').setAttribute("x", 100);

您可以使用X的值(在我的示例中为100)将标题向左或向右拖动。

答案 2 :(得分:0)

同样的问题,加上同一图表的图表标题长度可变,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;
}
相关问题