ng2-charts - 提示颜色与线条颜色不匹配

时间:2021-04-19 16:08:54

标签: angular chart.js

如何将工具提示颜色设置为我的线条颜色?
如您所见,收费提示颜色设置为默认值。

我在 angular 11 中使用 ng2-charts。

enter image description here

配置:

public chartType: ChartType = 'line';
public chartLabels: Label[]  = ['13.04', '14.04','15.04','16.04','17.04','18.04','19.04'];
public chartOptions: ChartOptions = {
  responsive: true,
  tooltips: {
    mode: 'index',
    intersect: false,
  },
  maintainAspectRatio: false,
  legend: {
    display: false,
  },
  scales: {
    xAxes:  [
      {
        gridLines: {
          drawBorder: false,
          display: false,
        },
      },
    ],
    yAxes: [
      {
        ticks: {
          maxTicksLimit: 3,
        },
        gridLines: {
          drawBorder: false,
        },
      },
    ],
  },
};
public chartData: ChartDataSets[] = [
  {
    type: 'line',
    label: 'This week',
    fill: false,
    pointRadius: 0,
    lineTension: 0,
    borderWidth: 2,
    borderColor: 'rgba(255, 0, 0, 1)',
    backgroundColor: 'rgba(255, 0, 0, 1)',
    data: [65, 59, 80, 81, 56, 55, 40],
  },
  {
    label: 'Last week',
    fill: false,
    pointRadius: 0,
    lineTension: 0,
    borderWidth: 2,
    borderColor: 'rgba(255, 0, 0, .3)',
    backgroundColor: 'rgba(255, 0, 0, .3)',
    borderDash: [5, 7],
    data: [28, 48, 40, 19, 86, 27, 90],
  },
];

模板:

<div class="chart">
  <canvas baseChart
          [datasets]="chartData"
          [labels]="chartLabels"
          [options]="chartOptions"
          [chartType]="chartType">
  </canvas>
</div>

1 个答案:

答案 0 :(得分:0)

我最终使用工具提示回调函数 labelColor 为给定的数据集索引设置了正确的颜色。

enter image description here

public chartOptions: ChartOptions = {
  responsive: true,
  tooltips: {
    mode: 'index',
    intersect: false,
    callbacks: {
      labelColor: function(context) {
        return {
            borderColor: context.datasetIndex === 0 ? 'rgba(255, 0, 0, 1)' : 'rgba(255, 0, 0, .3)',
            backgroundColor: context.datasetIndex === 0 ? 'rgba(255, 0, 0, 1)' : 'rgba(255, 0, 0, .3)',
        };
      },
    }
  },
  maintainAspectRatio: false,
  legend: {
    display: false,
  },
  scales: {
    xAxes:  [
      {
        gridLines: {
          drawBorder: false,
          display: false,
        },
      },
    ],
    yAxes: [
      {
        ticks: {
          maxTicksLimit: 3,
        },
        gridLines: {
          drawBorder: false,
        },
      },
    ],
  },
};