我试图绘制一个带有负值和正值的折线图,将其映射到具有相同颜色的各个象限,但是我想更改x轴上方和下方的线条颜色。
var data = new google.visualization.DataTable();
data.addColumn("string", "Year");
data.addColumn("number", "Effective Investible Surplus");
data.addRows(dataSet);
this.formatNumber.format(data,1);//indian currency format
var options = {
legend: this.legendStyle,
areaOpacity: 0.8,
backgroundColor: '#f5f1e7',
animation: {
startup: true,
duration: 300,
easing: 'linear',
},
hAxis: {
title: "Years",
titleTextStyle: this.chartTitleText
},
vAxis: {
title: "Rupees",
titleTextStyle: this.chartTitleText,
format: this.numberPattern
},
colors: ["#b3dda7"]
};
var chart = new google.visualization.AreaChart(
document.getElementById("chart_div")
);
chart.draw(data, options);
});
答案 0 :(得分:0)
首先,为了更改单个系列的颜色,
您将需要使用'style'
角色。
我们可以使用带有计算列的数据视图来确定每行应为哪种颜色。
但是,由于面积图的绘制方式很自然,
您将需要插入y轴值为0的行,
值与x轴交叉的所有位置。
否则,您将获得一个区域,每种颜色均分成两半。
下一步,因为您在x轴(离散轴)上使用字符串,
我们将不得不在每个必须插入新行的地方重复使用标签。
为避免这种情况,我们可以使用值为2的选项hAxis.showTextEvery
。
这样可以避免重复标签,
但也会导致某些标签不显示。
请参阅以下工作片段...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var dataSet = [
['2010', 0],
['2011', 20],
['2012', -40],
['2013', 10],
['2014', -10],
['2015', 20],
['2016', 10],
['2017', -20],
['2018', 20],
['2019', -20]
];
// add a value of zero where the value crosses the x-axis
for (var i = (dataSet.length - 1); i >= 0; i--) {
var val = dataSet[i][1];
if ((i-1) >= 0) {
var nextVal = dataSet[i-1][1];
if ((val >= 0) && (nextVal < 0)) {
dataSet.splice(i, 0, [dataSet[i][0], 0]);
} else if ((val < 0) && (nextVal >= 0)) {
dataSet.splice(i, 0, [dataSet[i][0], 0]);
}
}
}
var data = new google.visualization.DataTable();
data.addColumn('string', 'Year');
data.addColumn('number', 'Effective Investible Surplus');
data.addRows(dataSet);
// create data view to add color
var dataView = new google.visualization.DataView(data);
dataView.setColumns([
// include x & y column index
0, 1,
// add calculated color
{
calc: function(data, row) {
var color = '#b3dda7';
var val = data.getValue(row, 1);
var nextVal = 0;
if (row > 0) {
nextVal = data.getValue(row - 1, 1);
}
if ((val < 0) || ((val === 0) && (nextVal < 0))) {
color = '#f08080';
}
return color;
},
type: 'string',
role: 'style'
}
]);
var options = {
legend: 'none',
areaOpacity: 0.8,
backgroundColor: '#f5f1e7',
animation: {
startup: true,
duration: 300,
easing: 'linear',
},
hAxis: {
title: 'Years',
format: '0000',
showTextEvery: 2
},
vAxis: {
title: 'Rupees'
}
};
var chart = new google.visualization.AreaChart(document.getElementById("chart"));
chart.draw(dataView, options);
});
<div id="chart"></div>
<script src="https://www.gstatic.com/charts/loader.js"></script>