gpt4 book ai didi

javascript - Chart.js 有没有办法根据值对折线图刻度进行着色

转载 作者:行者123 更新时间:2023-12-01 00:53:55 26 4
gpt4 key购买 nike

我有简单的chart.js折线图: enter image description here

我需要根据之前的值对刻度之间的线条进行着色:

enter image description here

如果下一个值低于上一行,则必须为红色,如果更高,则为绿色。

有什么想法可以实现这一目标吗?

最佳答案

您可以检查以下解决方案。

var ctx = document.getElementById('myChart').getContext('2d');
//adding custom chart type
Chart.defaults.multicolorLine = Chart.defaults.line;
Chart.controllers.multicolorLine = Chart.controllers.line.extend({
draw: function(ease) {
var
startIndex = 0,
meta = this.getMeta(),
points = meta.data || [],
colors = this.getDataset().colors,
area = this.chart.chartArea,
originalDatasets = meta.dataset._children
.filter(function(data) {
return !isNaN(data._view.y);
});

function _setColor(newColor, meta) {
meta.dataset._view.borderColor = newColor;
}

if (!colors) {
Chart.controllers.line.prototype.draw.call(this, ease);
return;
}

for (var i = 2; i <= colors.length; i++) {
if (colors[i-1] !== colors[i]) {
_setColor(colors[i-1], meta);
meta.dataset._children = originalDatasets.slice(startIndex, i);
meta.dataset.draw();
startIndex = i - 1;
}
}

meta.dataset._children = originalDatasets.slice(startIndex);
meta.dataset.draw();
meta.dataset._children = originalDatasets;

points.forEach(function(point) {
point.draw(area);
});
}
});
// build colors sequence
const data = [0, 10, 5, 2, 20, 30, 45];
const availableColors = ['red', 'green'];
let colors = [];
data.forEach(item => {
availableColors.forEach(color => {
colors.push(color)
})
})

var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'multicolorLine',

// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
borderColor: 'rgb(255, 99, 132)',
data: data,
//first color is not important
colors: ['', ...colors]
}]
},

// Configuration options go here
options: {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.bundle.min.js"></script>
<canvas id="myChart"></canvas>

关于javascript - Chart.js 有没有办法根据值对折线图刻度进行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56751074/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com