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

问题描述 投票:0回答:2

我不明白如何根据 Chart.js 中的值制作自定义点颜色?

如果是 <= 0 then dots red color, if y(0-4) blue color, etc

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,

      }
    }
  }
})
javascript chart.js
2个回答
0
投票

您可以利用数据集的

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,
      }
    }
  }
})

0
投票

这可以通过使用

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>

© www.soinside.com 2019 - 2024. All rights reserved.