繁体   English   中英

在 Google 图表中居中对齐标题

[英]Center align title in Google Chart

如何在 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);

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

将页眉添加到页面:

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

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

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

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

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

你可以这样做:

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

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

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

暂无
暂无

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

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