简体   繁体   English

带有Angular-cli的D3 V4

[英]D3 V4 with Angular-cli

I am using D3 charting library to create charts with Angular-cli. 我正在使用D3图表库通过Angular-cli创建图表。 D3 version is 4.2.2 . D3版本是4.2.2 Following is what I am trying. 以下是我正在尝试的。

    import {Directive, ElementRef} from '@angular/core';
    import * as D3 from 'd3';

    @Directive({
      selector: 'bar-graph',
      properties: ['data'],
    })

    export class BarGraphDirective {

      private data:Array<number>;  // raw chart data
      private htmlElement:HTMLElement;

      constructor(elementRef:ElementRef) {
        this.htmlElement = elementRef.nativeElement;  // reference to <bar-graph> element from the main template
        console.log(this.htmlElement);
        console.log(D3);

        let d3:any = D3;

        var data = [{
          "date": "2011-10-01",
          "sales": 110,
          "searches": 172
        }, {
          "date": "2011-10-02",
          "sales": 51,
          "searches": 67
        }, {
          "date": "2011-10-03",
          "sales": 53,
          "searches": 69.4
        }];

        // set the dimensions and margins of the graph
        var margin = {
            top: 20,
            right: 80,
            bottom: 30,
            left: 50
          },
          width = 960 - margin.left - margin.right,
          height = 500 - margin.top - margin.bottom;

        // parse the date / time
        var parseDate = d3.timeParse("%Y-%m-%d");
        console.log(parseDate);

        // set the ranges
        var x = d3.scaleTime().range([0, width]);
        var y = d3.scaleLinear().range([height, 0]);

        // define the line
        var line = d3.line().curve(d3.curveBasis)
          .x(function (d) {
            return x(d.date);
          })
          .y(function (d) {
            return y(d.sales);
          });

        var svg = d3.select(this.htmlElement).append("svg")
          .attr("width", width + margin.left + margin.right)
          .attr("height", height + margin.top + margin.bottom)
          .append("g")
          .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

        var color = d3.scaleOrdinal(d3.schemeCategory10);

        // format the data
        data.forEach(function (d) {
          d.date = parseDate(d.date);
          d.sales = +d.sales;
        });

        x.domain(d3.extent(data, function (d) {
          return d.date;
        }));

        y.domain([0, d3.max(data, function (d) {
          return d.sales;
        })]);

        // Add the line path.
        svg.append("path")
          .data([data])
          .attr("class", "line")
          .style("fill", "none")
          .attr("d", line)
          .style("stroke", function (d) {
            return color(d.Austin);
          });

        // Add the X Axis
        svg.append("g")
          .attr("transform", "translate(0," + height + ")")
          .call(d3.axisBottom(x));

        // Add the Y Axis
        svg.append("g")
          .call(d3.axisLeft(y));
      }
    }

Then my chart looks as below. 然后我的图表如下所示。

在此处输入图片说明

The problems are X-axis & Y-axis names are missing, X-axis labels (dates) are not properly formatted. 问题是缺少X轴和Y轴名称,X轴标签(日期)的格式不正确。

node_modules folder has below D3 libraries. node_modules文件夹具有以下D3库。

在此处输入图片说明

And system.config.ts system.config.ts

    const map: any = {
      'd3': 'vendor/d3/build'
    };

    /** User packages configuration. */
    const packages: any = {
      'd3':{
        format: 'cjs',
        defaultExtension: 'js',
        main: 'd3.min.js'
      }
    };

angular-cli-build.js angular-cli-build.js

    // Angular-CLI build configuration
    // This file lists all the node_modules files that will be used in a build
    // Also see https://github.com/angular/angular-cli/wiki/3rd-party-libs

    /* global require, module */

    var Angular2App = require('angular-cli/lib/broccoli/angular2-app');

    module.exports = function(defaults) {
      return new Angular2App(defaults, {
        vendorNpmFiles: [
          ...
          'd3/**/*.+(js|js.map)'
        ]
      });
    };

Any suggestions are highly appreciated. 任何建议都将受到高度赞赏。

Thank You 谢谢

For formatting the x-axis ticks: 格式化x轴刻度:

svg.append("g")
            .attr("transform", "translate(0," + height + ")")
            .call(d3.axisBottom(x).tickFormat(d3.timeFormat("%Y-%m-%d")));

Adding labels: 添加标签:

svg.append("text")
            .attr("text-anchor", "middle")
            .attr("transform", "translate("+ (-margin.left/2) +","+(height/2)+")rotate(-90)")
            .text("Sales");

    svg.append("text")
            .attr("text-anchor", "middle")
            .attr("transform", "translate("+ (width/2) +","+(height+(margin.bottom))+")")
            .text("Date");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM