使用chart.js实现Angular数据可视化

问题描述 投票:-1回答:1

我有一个js文件,它从API中获取数据,并对其进行汇总,它提供的输出形式为:1月男5女8月男3女9月男6女2我想在Angular中使用chart.js或d3或ngx或任何可用的库将其可视化,图表应该是这样的。请在此输入图片描述

以下是我的JavaScript代码

global.fetch = require("cross-fetch");

fetch("https://pastebin.com/raw/fvJkWEk5")
   .then(response => {
      return response.json();
    })
   .then(json_data => {
      var months = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'];

     var months_data = [
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
      {female: 0, male: 0,},
   ];

    json_data.map((u,i) => {
       months_data[parseInt(u.data.registration_time.split("-")[1]) - 1][u.data.sex.toLowerCase()]++;
   })
    months_data.map((u,i) => {
      console.log(months[i] + "  male " +  u.male + " female " + u.female);
    })

    })
 .catch(err => {
  console.error(err);
  });
javascript angular chart.js visualization
1个回答
0
投票

例子 : https:/stackblitz.comeditangular-ivy-psxufv。

使用文件

https:/valor-software.comng2-charts#GeneralInfo。

第1步: npm install --save ng2-charts

第2步: npm install --save chart.js

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ChartsModule } from 'ng2-charts';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    ChartsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

data.service.ts - 更改为使用您的URL。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { InnerModel } from './model';

@Injectable({
  providedIn: 'root'
})
export class DataService {

  // url = 'https://pastebin.com/raw/fvJkWEk5';
  url = 'http://localhost:4200/assets/data.json';

  constructor(private http: HttpClient) { }

  getChartData(): Observable<any> {
    return this.http.get(this.url);
  }
}

模型.ts

export interface InnerModel {
  district_name: string;
  registration_time: string;
  sex: string;
  ctc_number: string;
}

export interface DataModel {
  id: string;
  data: InnerModel;
}

app.component.ts

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { DataService } from './data.service';
import { DataModel } from './model';
import { ChartOptions, ChartType, ChartDataSets } from 'chart.js';
import { Label } from 'ng2-charts';

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

  public barChartOptions: ChartOptions = {
    responsive: true,
    scales: { xAxes: [{}], yAxes: [{}] },
    plugins: {
      datalabels: {
        anchor: 'end',
        align: 'end',
      }
    }
  };

  public barChartType: ChartType = 'bar';
  public barChartLegend = true;

  private dataSubsctiption: Subscription;

  public chartData: ChartDataSets[] = [
    { data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], label: 'Male' },
    { data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], label: 'Female' }
  ];

  months: Label[] = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'August', 'Sept', 'Oct', 'Nov', 'Dec'];


  constructor(private dts: DataService) {
  }

  ngOnInit(): void {
    this.dataSubsctiption = this.dts.getChartData().subscribe(
      (jsonData: DataModel[]) => {
        const newData =  [
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
          [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        ];
        jsonData.map((u, i) => {
          const index = u.data.sex.toLowerCase() === 'male' ? 0 : 1;
          const dataSetItem = newData[index];
          // tslint:disable-next-line:radix
          dataSetItem[parseInt(u.data.registration_time.split('-')[1]) - 1]++;
        });

        this.chartData[0].data =  newData[0];
        this.chartData[1].data =  newData[1];
      },
      err => {
        console.error(err);
      });
  }

  ngOnDestroy(): void {
    this.dataSubsctiption.unsubscribe();
  }
}

app.component.html

<div>
  <div>
    <div style="display: block">
      <canvas baseChart
        [datasets]="chartData"
        [labels]="months"
        [options]="barChartOptions"
        [legend]="barChartLegend"
        [chartType]="barChartType">
      </canvas>
    </div>
  </div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.