Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/415.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用chart.js进行角度数据可视化_Javascript_Angular_Chart.js_Visualization - Fatal编程技术网

Javascript 使用chart.js进行角度数据可视化

Javascript 使用chart.js进行角度数据可视化,javascript,angular,chart.js,visualization,Javascript,Angular,Chart.js,Visualization,我有一个js文件,它从API中获取数据并进行汇总,它以 一月男5女8 二月男3女9 三月男6女2 我想使用chart.js或d3或ngx或任何可用的库在angular中可视化它。 图表应该是这样的 这是我的JavaScript代码 global.fetch = require("cross-fetch"); fetch("https://pastebin.com/raw/fvJkWEk5") .then(response => { return response.jso

我有一个js文件,它从API中获取数据并进行汇总,它以 一月男5女8 二月男3女9 三月男6女2 我想使用chart.js或d3或ngx或任何可用的库在angular中可视化它。 图表应该是这样的

这是我的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);
  });

示例

使用

步骤1:
npm安装--保存ng2图表

步骤2:
npm安装--保存chart.js

应用程序模块.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 { }
export interface InnerModel {
  district_name: string;
  registration_time: string;
  sex: string;
  ctc_number: string;
}

export interface DataModel {
  id: string;
  data: InnerModel;
}
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();
  }
}
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

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 { }
export interface InnerModel {
  district_name: string;
  registration_time: string;
  sex: string;
  ctc_number: string;
}

export interface DataModel {
  id: string;
  data: InnerModel;
}
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>


问题出在哪里?我想用角度将数据可视化,就像一个简单的任务,但我发现很难实现。你的问题中的
json_数据是什么?json_数据是来自API的数据,(我已经编辑过了,现在看起来很清楚)@sibabratswain