【发布时间】:2020-08-26 15:57:45
【问题描述】:
参考:https://developers.google.com/chart/interactive/docs/gallery/timeline#a-simple-example
在上图中,交替行具有背景色。 亚当斯是灰色的,而华盛顿和杰斐逊是白色的。 我想根据与该行相关的数据值之一为背景着色。
【问题讨论】:
标签: charts google-visualization
参考:https://developers.google.com/chart/interactive/docs/gallery/timeline#a-simple-example
在上图中,交替行具有背景色。 亚当斯是灰色的,而华盛顿和杰斐逊是白色的。 我想根据与该行相关的数据值之一为背景着色。
【问题讨论】:
标签: charts google-visualization
没有改变行背景颜色的标准选项。
但可以在图表的'ready' 事件上手动更改颜色。
背景行将使用<rect> 元素绘制。
当事件触发时,通过测试以下属性找到元素。
x - 所有值都为零 --> x="0"stroke - 只有整体背景 <rect> 将具有除 "none" 之外的笔画属性
然后将fill 属性设置为您选择的颜色。
// make sure rect is a background row
if ((rect.getAttribute('x') === '0') && (rect.getAttribute('stroke') === 'none')) {
// determine existing color
if (rect.getAttribute('fill') === '#ffffff') {
rect.setAttribute('fill', 'cyan');
} else {
rect.setAttribute('fill', 'magenta');
}
}
请参阅以下工作 sn-p...
google.charts.load('current', {
packages: ['timeline']
}).then(function () {
var container = document.getElementById('chart');
var chart = new google.visualization.Timeline(container);
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({type: 'string', id: 'President'});
dataTable.addColumn({type: 'date', id: 'Start'});
dataTable.addColumn({type: 'date', id: 'End'});
dataTable.addRows([
['Washington', new Date(1789, 3, 30), new Date(1797, 2, 4)],
['Adams', new Date(1797, 2, 4), new Date(1801, 2, 4)],
['Jefferson', new Date(1801, 2, 4), new Date(1809, 2, 4)]
]);
google.visualization.events.addListener(chart, 'ready', function () {
var rects = container.getElementsByTagName('rect');
Array.prototype.forEach.call(rects, function(rect) {
// make sure rect is a background row
if ((rect.getAttribute('x') === '0') && (rect.getAttribute('stroke') === 'none')) {
// determine existing color
if (rect.getAttribute('fill') === '#ffffff') {
rect.setAttribute('fill', 'cyan');
} else {
rect.setAttribute('fill', 'magenta');
}
}
});
});
chart.draw(dataTable);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart"></div>
【讨论】: