【问题标题】:Center align title in Google Chart在 Google 图表中居中对齐标题
【发布时间】:2014-10-13 10:52:39
【问题描述】:

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

【问题讨论】:

  • 我以前从未使用过 Google Charts API,它有任何 .css 文件吗?如果是,如果您提供 html 和 css 文件,也许我可以帮助您通过 css 设置标题对齐方式。

标签: javascript html charts


【解决方案1】:

我要做的是从图表中删除标题并在图表上方添加一个标题,以便您使用 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

【讨论】:

  • 同意,没有其他选项可以使标题居中。你只能删除它。从图表中删除标题的简单方法是从选项中删除“标题:”。
  • 在我的情况下,将titlePosition设置为'none'后,标题不显示并且顶部存在大边距..有没有办法隐藏标题并让图表的其他组件自动填充这个空间?
  • 第二个选项后缺少逗号
【解决方案2】:

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

你可以这样做:

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

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-18
      • 1970-01-01
      • 1970-01-01
      • 2018-05-01
      相关资源
      最近更新 更多