我想使用chart.js(www.chartjs.org)创建条形图。条形填充颜色应根据值而变化。
例如,如果该值小于10,则颜色为绿色,11-15表示黄色,而16-20为红色。
是否有可能通过chart.js做到这一点,以及如何做到?
我从未使用过chart.js,但这是我的建议...
Chart.defaults.global = { //this has all the information for the chart, I just removed everything else
// String - Colour of the scale line
scaleLineColor: "rgba(0,0,0,.1)"
}
我会喜欢....
if (number < 10) { Chart.defaults.global.scaleLineColor = "rgba(whatever)" }
然后只需将您的所有代码等填充。希望这会有所帮助!
我没有找到使用chart.js进行此操作的方法,而是切换到了Google可视化。
可以这样做:
// first index in chartData array describes the fields in the following indexes,
// The first two are the X and Y values, role: style tells the chart to use the third
// field as the style of that particular bar. role: annotation tells the chart to
// add the contents of the fourth field as a label to each bar.
var chartHeader = [['Time', 'Measurement', { role: 'style' }, { role: 'annotation' }]];
function ConvertJsonToChartData(json) {
var chartData = chartHeader;
for (var key in json) {
var x = json[key].X;
var elapsedTime = json[key].ElapsedTime;
// set style based on value of elapsedTime
var style = 'black';
if (elapsedTime > GlobalSettings['criticalThreshold']) {
style = GlobalSettings['criticalColor'];
} else if(elapsedTime > GlobalSettings['warningThreshold']) {
style = GlobalSettings['warningColor'];
}
// add a new datapoint to the chart
chartData.push([x, elapsedTime, style, elapsedTime]);
}
return chartData;
}
function MakeHourGraph(json) {
var chartData = ConvertJsonToChartData(json);
var data = google.visualization.arrayToDataTable(chartData);
var options = {
title: 'Response Times',
hAxis: { title: 'Hour', titleTextStyle: { color: 'blue' } },
vAxis: { title: 'msecs', titleTextStyle: { color: 'blue' } },
legend: { position: "none" }
};
var chart = new google.visualization.ColumnChart(document.getElementById('hour_chart_div'));
chart.draw(data, options);
}
非常古老的帖子,但是对于那些来自Google搜索的人来说,is是使用ChartJS做到这一点的一种方法。
您可以将数据转换为2个数据集:-第一个为正值,所有负值均替换为0-第二个为负值,将所有正值替换为0
originalSet = [1,-1, 3,-3, 5]
positiveSet = [1, 0, 3, 0, 5]
negativeSet = [0,-1, 0,-3, 0]
然后只需为每组添加您选择的颜色:
datasets: [
{ data: positiveSet, backgroundColor: 'rgba(0,255,0,0.5)' },
{ data: negativeSet, backgroundColor: 'rgba(255,0,0,0.5)' }
]
此方法不仅可以应用于正/负分隔,而且通常还可以用于基于值进行样式设置的情况。