javascript 如何在Chart.js中使自定义点颜色依赖于值?

blpfk2vs  于 2023-08-02  发布在  Java
关注(0)|答案(2)|浏览(110)

我不明白如何在Chart.js中根据值定制点颜色?
如果y <= 0则点红色,如果y(0-4)则点蓝色,等等

const ctx = document.getElementById('chart');
const request = [
  {x: 'Station1',y: 5},
  {x: 'Station2',y: 2},
  {x: 'Station3',y: 1},
  {x: 'Station4',y: 8},
  {x: 'Station5',y: 7},
  {x: 'Station6',y: -2},
  {x: 'Station7',y: 10},
  {x: 'Station8',y: 0}
]

const labels = request.map(function(e) {return e.x;});

const fuelChart = new Chart(ctx,{
  type:'scatter',
  data: {
    datasets: [{
      data: request,
      label:'Day to posts'
    }]
  },
  options: {
    responsive: true,
    scales:{
      x:{
        type:'category',
        labels:labels,

      }
    }
  }
})

字符串

s2j5cfk0

s2j5cfk01#

你可以使用dataset的backgroundColor属性,并向它传递一个数组。数组可以基于数据构建,因此您可以添加自己的逻辑来返回所需的颜色。
大概是这样的:

const ctx = document.getElementById('myChart');

const request = [
      {x: 'Station1',y: 5},
      {x: 'Station2',y: 2},
      {x: 'Station3',y: 1},
      {x: 'Station4',y: 8},
      {x: 'Station5',y: 7},
      {x: 'Station6',y: -2},
      {x: 'Station7',y: 10},
      {x: 'Station8',y: 0}
]

const labels = request.map(function(e) { return e.x; });
const colors = request.map(function(e) {
  if (e.y <= 0) {
    return '#ff6384'
  } else if (e.y >= 0 && e.y <= 4) {
    return '#36a2eb';
  } else {
    return '#cc65fe';
  }
});

const fuelChart = new Chart(ctx, {
  type: 'scatter',
  data: {
    datasets: [{
      data: request,
      label: 'Day to posts',
      backgroundColor: colors
    }]
  },
  options: {
    responsive: true,
    scales: {
      x: {
        type: 'category',
        labels: labels,
      }
    }
  }
})

字符串

hyrbngr7

hyrbngr72#

这可以通过使用Arrays.map()来完成,如下所示:

backgroundColor: request.map(o => o.y < 0 ? 'red' : 'blue')

字符串
请看一下下面修改后的可运行代码,看看它是如何工作的。

const ctx = document.getElementById('chart');
const request = [
  {x: 'Station1',y: 5},
  {x: 'Station2',y: 2},
  {x: 'Station3',y: 1},
  {x: 'Station4',y: 8},
  {x: 'Station5',y: 7},
  {x: 'Station6',y: -2},
  {x: 'Station7',y: 10},
  {x: 'Station8',y: 0}
]

const labels = request.map(function(e) {return e.x;});

const fuelChart = new Chart(ctx,{
  type:'scatter',
  data: {
    datasets: [{
      data: request,
      label:'Day to posts',
      backgroundColor: request.map(o => o.y < 0 ? 'red' : 'blue')
    }]
  },
  options: {
    responsive: true,
    scales:{
      x:{
        type:'category',
        labels:labels
      }
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/chart.js@4"></script>
<canvas id="chart" height="80"></canvas>

的数据

相关问题