悬停时的Chartjs / ng2-charts行不起作用 [英] Chartjs / ng2-charts line on hover does not work

查看:55
本文介绍了悬停时的Chartjs / ng2-charts行不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Angular cli应用程序上的ng2-charts优化我的图表。通常,一切正常,唯一的事情不是悬停线来跟踪数据点。这是我尝试制作的理想图表模型,并且我也尝试遵循其代码:

I'm trying to optimize my chart using ng2-charts on Angular cli app. In general, everything works just fine, the only thing does not is the line on hover to track the data point. This is the ideal chart model I try to make and I also tried to follow its code:

https://stackblitz.com/edit/line-chart?file=app%2Fapp.component.ts

但是,当我将鼠标悬停在图表上时,仅显示工具提示。

However, when I hover on my chart, only the tooltip is shown.

这是我的代码:

plugin-hoverline.ts :(复制并粘贴以下链接,@ GRUNT表示感谢)

plugin-hoverline.ts: (copy & paste from the link below, credit by @GRUNT)

https://istack.000webhostapp.com/chartjs-plugin-hoverline.js

banner.component.ts :(图表部分)

banner.component.ts: (chart component)

import { Component, OnInit } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import './plugin-hoverline';

@Component({
  selector: 'app-banner',
  templateUrl: './banner.component.html',
  styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {

  currentDate:string = new Date().toJSON().slice(0,10).replace(/-/g,'-');

  private dataUrl: string = 'historical/close.json?start=2013-09-01&end=' + this.currentDate;

  constructor(    
    private historicalBpiService:HistoricalBpiService
  ) {}

  // lineChart

  public lineChartData:any = [
    { data:[], label: 'BTC' }
  ];

  public lineChartLabels:Array<any> = [];

  public lineChartOptions:any = {
    responsive: true,
    maintainAspectRatio: false,
    layout: {
      padding: 0
    },
    lineOnHover: {
     enabled: true,
     lineColor: '#bbb',
     lineWidth: 1
   },
    scales: {
      yAxes: [{
        display: false,
        scaleLabel: {
          display: false,
          labelString: 'USD'
        },
        ticks: {
          //min: 0,
          //max: 5000,
          stepSize: 500,
          display: false,
          mirror: true,
          labelOffset: 7,
          padding: -10,
          callback: function(value, index, values) {
            return '$' + value;
          }
        },
        gridLines: {
          display: true,
          tickMarkLength: 0
        }
      }],
      xAxes: [{
        ticks: {
          display: false,
          mirror: true
        },
        gridLines: {
          display: false,
          tickMarkLength: 0
        }
      }]
    },
    elements: {
      point: {
        radius: 0
      },
      line: {
        tension: 0, // 0 disables bezier curves
      }
    },
    hover: {
      mode: 'nearest',
      intersect: false
    },
    tooltips: {
      mode: 'nearest',
      intersect: false,
      backgroundColor: 'rgb(95,22,21)',
      callbacks: {
        title: function (tooltipItems, data) {
          return (tooltipItems[0] || {})['xLabel'];
        },
        label: function (tooltipItem, data) {
          return '$ ' + tooltipItem.yLabel.toLocaleString();
        },
        labelColor: function(tooltipItem, chart) {
          let dataset = chart.config.data.datasets[tooltipItem.datasetIndex];
          return {
            backgroundColor : dataset.backgroundColor
          }
        }
      }
    }
  };
  public lineChartColors:Array<any> = [
    {
      backgroundColor: 'rgba(199,32,48,0.9',
      borderColor: 'rgb(95,22,21);',
      pointBackgroundColor: 'rgba(218,208,163,0.9)',
      pointHoverBackgroundColor: 'rgba(218,208,163,0.9)',
      pointHoverBorderColor: 'rgb(218,208,163)',
      pointHoverRadius: 5,
      steppedLine: false

    }
  ];
  public lineChartLegend:boolean = false;
  public lineChartType:string = 'line';


  // events
  public chartClicked(e:any):void {
    console.log(e);
  }

  public chartHovered(e:any):void {
    console.log(e);
  }

  ngOnInit(){
    this.historicalBpiService.getBpiData(this.dataUrl)
      .subscribe(
        res => {
          //this.lineChartData = Object.keys(res.bpi).map(function (key) { return res.bpi[key];});
          this.lineChartData[0].data = Object.values(res.bpi);
          this.lineChartLabels = Object.keys(res.bpi);
          //console.log(this.lineChartData,this.lineChartLabels);
        }
      )
  }
}

模板:

<div class="chart">
      <canvas baseChart height="360px"
        [datasets]="lineChartData"
        [labels]="lineChartLabels"
        [options]="lineChartOptions"
        [colors]="lineChartColors"
        [legend]="lineChartLegend"
        [chartType]="lineChartType"
        (chartHover)="chartHovered($event)"
        (chartClick)="chartClicked($event)"></canvas>
    </div>


推荐答案

使用以下代码尝试:

图表组件

import { Component, OnInit } from '@angular/core';
import { HistoricalBpiService } from '../../services/historical-bpi.service';
import './plugin-hoverline';

@Component({
   selector: 'app-banner',
   templateUrl: './banner.component.html',
   styleUrls: ['./banner.component.scss']
})
export class BannerComponent implements OnInit {

   currentDate: string = new Date().toJSON().slice(0, 10).replace(/-/g, '-');

   private dataUrl: string = 'historical/close.json?start=2013-09-01&end=' + this.currentDate;

   constructor(
      private historicalBpiService: HistoricalBpiService
   ) { }

   // lineChart

   public lineChartData: any = [
      { data: [], label: 'BTC', pointHoverRadius: 5, steppedLine: false }
   ];

   public lineChartLabels: Array<any> = [];

   public lineChartOptions: any = {
      responsive: true,
      maintainAspectRatio: false,
      layout: {
         padding: 0
      },
      lineOnHover: {
         enabled: true,
         lineColor: '#bbb',
         lineWidth: 1
      },
      scales: {
         yAxes: [{
            display: false,
            scaleLabel: {
               display: false,
               labelString: 'USD'
            },
            ticks: {
               //min: 0,
               //max: 5000,
               stepSize: 500,
               display: false,
               mirror: true,
               labelOffset: 7,
               padding: -10,
               callback: function (value, index, values) {
                  return '$' + value;
               }
            },
            gridLines: {
               display: true,
               tickMarkLength: 0
            }
         }],
         xAxes: [{
            ticks: {
               display: false,
               mirror: true
            },
            gridLines: {
               display: false,
               tickMarkLength: 0
            }
         }]
      },
      elements: {
         point: {
            radius: 0
         },
         line: {
            tension: 0, // 0 disables bezier curves
         }
      },
      hover: {
         mode: 'nearest',
         intersect: true
      },
      tooltips: {
         mode: 'nearest',
         intersect: true,
         backgroundColor: 'rgb(95,22,21)',
         callbacks: {
            title: function (tooltipItems, data) {
               return (tooltipItems[0] || {})['xLabel'];
            },
            label: function (tooltipItem, data) {
               return '$ ' + tooltipItem.yLabel.toLocaleString();
            },
            labelColor: function (tooltipItem, chart) {
               let dataset = chart.config.data.datasets[tooltipItem.datasetIndex];
               return {
                  backgroundColor: dataset.backgroundColor
               }
            }
         }
      }
   };
   public lineChartColors: Array<any> = [
      {
         backgroundColor: 'rgba(199,32,48,0.9',
         borderColor: 'rgb(95,22,21);',
         pointBackgroundColor: 'rgba(218,208,163,0.9)',
         pointHoverBackgroundColor: 'rgba(218,208,163,0.9)',
         pointHoverBorderColor: 'rgb(218,208,163)'

      }
   ];
   public lineChartLegend: boolean = false;
   public lineChartType: string = 'line';


   // events
   public chartClicked(e: any): void {
      console.log(e);
   }

   public chartHovered(e: any): void {
      console.log(e);
   }

   ngOnInit() {
      this.historicalBpiService.getBpiData(this.dataUrl)
         .subscribe(
         res => {
            //this.lineChartData = Object.keys(res.bpi).map(function (key) { return res.bpi[key];});
            this.lineChartData[0].data = Object.values(res.bpi);
            this.lineChartLabels = Object.keys(res.bpi);
            //console.log(this.lineChartData,this.lineChartLabels);
         }
         )
   }
}

您应该在 lineChartData 数组内而不是 lineChartColors内设置 pointHoverRadius 属性,还将 intersect 属性设置为 true 悬停工具提示

You should set the pointHoverRadius property inside lineChartData array instead of lineChartColors, also set the intersect property to true for both hover and tooltips

这篇关于悬停时的Chartjs / ng2-charts行不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆