簡體   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