首页 > 解决方案 > 图表JS根据数据值改变pointBackgroundColor

问题描述

所以我使用 Chartjs 创建了一个基本的折线图。我将如何根据数据的值更改点的颜色(pointBackgroundColor)?例如,如果数据点小于 10 则变为红色,或者如果数据点在 10 到 20 之间则变为蓝色?

const CHART = document.getElementById("lineChart");		
let lineChart = new Chart(CHART, {
	type: 'line',
	data: {
		labels: ["5/10/2010", "5/11/2010", "5/12/2010", "5/13/2010", "5/14/2010", "5/15/2010", "5/16/2010"],
		datasets: [
		{
			label: "Theta",
			fill: false,
			lineTension: 0,
			backgroundColor: "rgba(75,192,192,0.4)",
			borderColor: "rgba(9,31,62)",
			borderCapStyle: 'butt',
			borderDash: [],
			borderDashOffset: 0.0,
			borderJoinStyle: 'miter',
			pointBorderColor: "rgba(0,191,255)",
			pointBackgroundColor: "rgba(0,191,255)",
			pointBorderWidth: 5,
			pointBorderRadius: 5,
			pointHoverBackgroundColor: "rgba(75,192,192,1)",
			pointHoverBorderColor: "rgba(220,220,220,1)",
			pointHoverBorderWidth: 2,
			pointRadius: 1,
			pointHitRadius: 10,
			data: [15, 28, 11, 3, 34, 65, 20],
		}
	]
},
	options: {
	maintainAspectRatio: false,
	responsive: true,
	legend: {
		display: false,
	},
	scales: {
		yAxes:[{
		ticks: {
			fontColor: "#091F3e",
			beginAtZero: true,
			steps: 10,
			stepSize: 10,
			max: 100
			},
		gridLines: {
			display: false
		}
		
		}],
	xAxes:[{
		ticks: {
			fontColor: "#091F3e",
			fontSize: "10",
			},
		gridLines: {
			display: false
		}
		
		}]
	}
	}
});

标签: colorsbackgroundchart.jspointlinechart

解决方案


您可以在任何选项上使用闭包并根据上下文操作返回的值。pointBackgroundColor在下面的示例中,当当前值大于 0 时,我是红色的,否则是蓝色的。

pointBackgroundColor: function (context) {
  let value = context.dataset.data[context.dataIndex];

  return value > 0
    ? 'red'
    : 'blue';
},

推荐阅读