簡體   English   中英

使用兩個 JSON 對象在 Typescript / Angular 中使 Chart.JS 條形圖動態化

[英]Using two JSON objects to make Chart.JS Bar Chart Dynamic in Typescript / Angular

我正在使用 Chart.JS 制作條形圖,但我在使用我創建的兩個 JSON 對象來使圖表動態化時遇到問題。 我不確定我應該如何做到這一點,但對象可以改變值,我想讓圖表支持這一點。

這是我的標簽對象:

0: {labelName: "Plan Miles"}
1: {labelName: "Actual Miles"}
2: {labelName: "Route Variance"}

我的數據集有一個類似的對象。

對象值可以是任何數字,所以我想讓我的圖表動態以支持這一點。

我可以在我的代碼中更改什么來實現這一點?

我想刪除第二個和第三個數據點,並且只有一個數據集可以支持圖表中的多個條形。 所以我想通過標簽JSON對象和數據JSON對象循環或映射來制作圖表。

charts.component.ts

    export class ChartsComponent implements OnInit {

  canvas: any;
  ctx: any;
  ChartData: any;
  labelNames: any;
  
  constructor() {}
  ngOnInit(): void {
      // Charts
      this.canvas = document.getElementById('viewChart');
      this.ctx = this.canvas.getContext('2d');

      this.ChartData = JSON.parse(localStorage.getItem('ChartData'));

      const data = this.ChartData;

         //Label Object for Chart
         this.labelNames = JSON.parse(localStorage.getItem('LabelNames'));

         const labelNames = this.labelNames;
           const labelObject = [];
   
         // tslint:disable-next-line: prefer-for-of
         for(let i = 0; i < labelNames.length; i++) {
             const obj = labelNames[i].propertyName;
   
             labelObject.push({labelName: obj});
         }
   
         const newLabelObject = labelObject.slice(3, 5 + 1)
   
         console.log('Labels: ', newLabelObject);

         // tslint:disable-next-line: only-arrow-functions
         const barLabel = newLabelObject.map(function (e) {
           return e[1];
         })

      // tslint:disable-next-line: only-arrow-functions
      const driverLabel = data.map(function (e: any[]) {
          return e[1];
        });

      // tslint:disable-next-line: only-arrow-functions
        const firstDataPoint = data.map(function (e: any[]) {
          return e[3];
        });

      // tslint:disable-next-line: only-arrow-functions
        const secondDataPoint = data.map(function (e: any[]) {
          return e[4];
        });

       // tslint:disable-next-line: only-arrow-functions
        const thirdDataPoint = data.map(function (e: any[]) {
          return e[5];
        });

      const viewChart = new Chart(this.ctx, {
          type: 'bar',
          data: {
              labels: driverLabel,
              datasets: [
                  {
                  label: `newLabelObject`,
                  data: firstDataPoint,
                  backgroundColor: 'rgb(34, 167, 240)',
                  borderWidth: 1
              },
              {
                  label: 'Actual Miles',
                  data: secondDataPoint,
                  backgroundColor: 'rgb(240, 52, 52)',
                  borderWidth: 1
              },
              {
                  label: 'Route Variance',
                  data: thirdDataPoint,
                  backgroundColor: 'rgba(254, 241, 96, 1)',
                  borderWidth: 1
              }
          ]
          },

如果可能,我認為如果您使用與您的 Angular 版本完全兼容的圖表版本會更好,例如:

但是如果你真的需要使用這個版本,你可以創建一個包含兩個值的數組並迭代這個數組來創建你的值:

let labels = [{label: "A"}, {label: "B"}, {label: "C"}, {label: "D"}, {label: "E"}];
let values = [{value: 1}, {value: 2}, {value: 3}, {value: 4}, {value: 5}];
let finalArray = [];
labels.forEach((currentLabel, index) => {
    finalArray.push({ label: currentLabel.label, value: values[index].value});
});
/* finalArray will be: 
[
   {label: "A", value: 1}
   {label: "B", value: 2}
   {label: "C", value: 3}
   {label: "D", value: 4}
   {label: "E", value: 5}
];

*/

chart.js 文檔可能是構建輸入數據的最佳資源。 根據我對您的問題的理解,您想在同一圖表中的條形圖之間切換,對嗎? 我整理了一個在 angular 中使用 chart.js 的小堆棧閃電戰示例來做到這一點。 基本上,圖表配置對象定義了繪制的內容。 這需要根據您想要繪制和重新渲染的數據進行交換。 希望這有幫助/相關。 如果我誤解了你的問題,我深表歉意。

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { Chart } from 'chart.js';


const dataset1 = {
                  labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
                  datasets: [{
                      label: '# of Votes',
                      data: [12, 19, 3, 5, 2, 3],
                  }]
              };

const dataset2 = {
    labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
    datasets: [{
        label: '# of People',
        data: [3, 5, 2, 12, 19, 3],
    }]
};

@Component({
  selector: 'app-chart',
  templateUrl: './chart.component.html',
  styleUrls: ['./chart.component.css']
})
export class ChartComponent implements OnInit {
  chart: Chart;

  @ViewChild('graph', { static: true }) 
  graph: ElementRef;

  ctx: CanvasRenderingContext2D;

  currentDataSet = dataset1;
  
  constructor() {}

  ngOnInit() {
    this.ctx = (<HTMLCanvasElement>this.graph.nativeElement).getContext(
      '2d',
    );

    this.renderChart();
  }

  renderChart(){
    this.chart = new Chart(this.ctx, this.chartConfig);
  }

  pick(dataSet){
    this.currentDataSet = dataSet === 1 ? dataset1 : dataset2;
    this.renderChart();
  }

  get chartConfig(): Chart.ChartConfiguration {
    return  {
              type: 'bar',
              data: this.currentDataSet,
              options: {
                  scales: {
                      yAxes: [{
                          ticks: {
                              beginAtZero: true
                          }
                      }]
                  }
              }
          }
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM