GithubHelp home page GithubHelp logo

d3-ng2-service's Introduction

D3 Service for Angular

Build Status

Content

Introduction

D3, Mike Bostockโ€™s famed data visualization tool, underwent a major overhaul with version 4. Similarly, Angular 2 was a material departure from its predecessor.

With the release of version 4, D3 has been completely modularized and seen enhancements, which make it all the more powerful, yet easy to use.

Amongst the many changes since the release of Angular 2, the native support for developing at scale in TypeScript and the overhauled componentized structure are but two.

Combining the power of D3 and Angular can be challenging at first. The intent of this package is to provide a simple way to access D3 as an Angular service for use by components requiring the kind of sophisticated visualization support D3 excels at. The package includes TypeScript definitions to improve development experience and code maintainability.

Intended Use

This package was designed to quickly add D3 support to an Angular application, such as those created with the angular-cli.

As is clear from the D3 scope described below, there may be circumstances, where a smaller or larger D3 feature set may be better suited for a given project. In such cases, reviewing the TypeScript source code in this package's Github repo may serve as a starting point for a more tailored solution.

A suggested approach may also involve starting out with the d3-ng2-service for rapid prototyping. Then, once there is more stability regarding the specific, required D3 feature set, the D3 service pattern can be preserved by implementing the minimally viable D3 service directly in the project. This amounts to manually "treeshaking" D3 in order to preserve the convenience of accessing D3 functions through a d3 object.

For those interested in using the treeshaking performed "automatically" by third party build/bundling tools, it may be better to import the minimally required D3 functionality directly at component level. Following this strategy, may require added care to mind D3 cross-module prototype extensions (i.e. ordering of imports) and ensuring a live-binding to d3.event is in place, if any functionality based on d3.event is used.

Scope of D3 Functionality

As this package is designed for use with Angular, it does not strictly mirror the functionality scope included in the D3 Standard Bundle.

The d3-fetch module has been omitted as a design choice given the feature set of Angular. By implication, it is recommended to utilize e.g. Angular's HttpClient for client/server communication. The d3-ng2-service package does, however, expose D3 data parsing functionality such as csvParse(...).

The functionality enhancements provided by the now separate d3-selection-multi module have been included for added convenience.

For a complete list of D3 modules included, please refer to the package.json dependencies here. At present, included modules are provided in their entirety.

Installation

To include the package into your Angular project, simply use the standard npm package installation command:

npm install d3-ng2-service --save

Please note that the package has a peer dependency on @angular/core.

Usage

Once the module d3-ng2-service has been added to a project as described above, it provides the following importable exports:

  • D3Service: The Angular D3 Service injectable,
  • D3: A TypeScript type alias for the d3 variable which can be obtained from the D3Service, and
  • the various TypeScript interfaces and type aliases which are related to the D3 modules constituting d3 as provided by this service (e.g. Selection, Transition, Axis).

To obtain the d3 object from an injected D3 service d3Service: D3Service, it offers a method d3Service.getD3() with return type D3.

The below code snippets assume the use of TypeScript.

Step 1 - Registering the Service with an Angular Module

Import the Angular service and register it as a provider with an Angular module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ApplicationRef } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

import { D3Service } from 'd3-ng2-service'; // <-- import statement


@NgModule({
  declarations: [
    AppComponent,
    TestD3Component // <-- declaration of the D3 Test component used below
  ],
  imports: [
    BrowserModule,
    CommonModule,
    FormsModule
  ],
  providers: [D3Service], // <-- provider registration
  entryComponents: [AppComponent],
  bootstrap: [AppComponent]
})
export class AppModule {

}

Step 2 - Using the Service with an Angular Component

Important: The component is declared in the same module as the D3Service provider has been registered. Import the D3 service and then pass the service into the component constructor together with ElementRef. Obtain d3 from the D3 service and use it to perform the required tasks.

import { Component, OnInit, ElementRef } from '@angular/core';
import { D3Service, D3, Selection } from 'd3-ng2-service'; // <-- import the D3 Service, the type alias for the d3 variable and the Selection interface

@Component({
  selector: 'app-test-d3',
  templateUrl: 'test-d3.component.html',
  styleUrls: ['test-d33.component.css']
})
export class TestD3Component implements OnInit {

  private d3: D3; // <-- Define the private member which will hold the d3 reference
  private parentNativeElement: any;

  constructor(element: ElementRef, d3Service: D3Service) { // <-- pass the D3 Service into the constructor
    this.d3 = d3Service.getD3(); // <-- obtain the d3 object from the D3 Service
    this.parentNativeElement = element.nativeElement;
  }

  ngOnInit() {
    let d3 = this.d3; // <-- for convenience use a block scope variable
    let d3ParentElement: Selection<any, any, any, any>; // <-- Use the Selection interface (very basic here for illustration only)

// ...

    if (this.parentNativeElement !== null) {

      d3ParentElement = d3.select(this.parentNativeElement); // <-- use the D3 select method 

      // Do more D3 things 

    }
  }

}

Demo Project

For a more complete worked example of how this module can be used in an angular-cli created D3 Demo App, please see:

d3-ng2-service's People

Contributors

h-l avatar tomwanzek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

d3-ng2-service's Issues

dx and dy are NaN in cluster function

I try to reproduce this example:
https://bl.ocks.org/mattgiguere/339843b4622a965048fc9f61598f2d47
in Angular 2 using d3-ng2-service.

Surprisingly, it fails because the cluster() function returns bad x and y (they are all NaN).
It comes from here:
https://github.com/d3/d3-hierarchy/blob/master/src/cluster.js#L62
where dx and dy are both NaN even if they are declared here:
https://github.com/d3/d3-hierarchy/blob/master/src/cluster.js#L35

Nevertheless I do not think it is a D3 bug (as the example is running fine), so I guess it comes from my usage of d3-ng2-service.
Any hints?

My code is here: https://gist.github.com/ebrehault/d4ef30dcd3d5c21c748efc3afee5d176#file-content-tree-component-ts
and the console.log in line 69 shows x and y NaN values.

[d3-scale] Can't pass string range to linear scale

Passing string range to scaleLinear like so:

import * as d3Scale from 'd3-scale';

d3Scale.scaleLinear()
  .domain([1, 20])
  .clamp(true)
  .range(['#fff', '#000']);

Argument of type 'string[]' is not assignable to parameter of type 'number[]'.

As seen here, this should be possible:

Unlike the domain, elements in the given array need not be numbers; any value that is supported by the underlying interpolator will work

selection-multi not available

Hey there,

I'm having trouble using the "styles" and "attrs" method on Selections. I looked through the source and it seems the d3-selection-multi package gets exported in the src/bundle-d3.d.ts file but not in src/bundle-d3.js. When I manually add a line that exports everything from d3-selection-multi, I can use "styles" and "attrs".

bundle-d3.js (excerpt):

export * from 'd3-scale';
export * from 'd3-selection';
export * from 'd3-shape';

bundle-d3.d.ts (excerpt):

export * from 'd3-scale';
export * from 'd3-selection';
export * from 'd3-selection-multi';
export * from 'd3-shape';

Thanks for you time and for your awesome work!

How to use the d3js v4 typings standalone?

This Project looks great and once it is compatibile with ng 2.0 I will defenitly use it,
but for now I would really like to install the d3 typings for d3 version 4.

I'm using typescript 2 and as far as I understand your comment on DefinitelyTyped/DefinitelyTyped#9936 I should be able to use them today.
But I dont get how..

I tried:
npm i @types/d3 this installs the typings for d3 version 3
npm i @types/d3-types-2.0 npm ERR!
npm i @types/[email protected] npm ERR!
npm i @types/[email protected] npm ERR!

Thanks for all your work on the typings ๐Ÿ‘

Update d3-voronoi to 1.1.0:

  • update dependencies for module
  • update definitions dependency
  • Review barrel to ensure they are complete for VoronoiDiagram's new find-method

How to draw a d3 stack barchart using ng-2service?

I am trying to draw a stack bar chart (like this code https://bl.ocks.org/DimsumPanda/689368252f55179e12185e13c5ed1fee
) using d3-ng2 service, in a Angularjs2 component. The following line works in Javascript:

var datasample="ethnicity,F Under 25,F Over 75,F 25 to 50,F 50 to 75,M Under 25,M Over 75,M 25 to 50,M 50 to 75\n"+
"Asian,327,296,332,309,306,330,307,323\n"+
"Black,294,302,330,305,295,363,322,292";
var data= this.d3.csvParse(datasample);
g.selectAll(".serie")
.data(d3.stack().keys(data.columns.slice(1))(data)

However, I get the following error, when I use it in typescript inside the component.

Argument of type 'DSVParsedArray' is not assignable to parameter of type '{ [key: string]: number; }[]'.
Types of property 'includes' are incompatible.
Type '(searchElement: DSVRowString, fromIndex?: number) => boolean' is not assignable to type '(searchElement: { [key: string]: number; }, fromIndex?: number) => boolean'.
Types of parameters 'searchElement' and 'searchElement' are incompatible.
Type '{ [key: string]: number; }' is not assignable to type 'DSVRowString'.
Index signatures are incompatible.
Type 'number' is not assignable to type 'string'.

I import d3-ngservice to use d3 object.

import { D3Service, D3, Selection } from 'd3-ng2-service';
It seems I should rewrite d3.stack().keys line in a typescript format. I tried to import 'Stack' class from ng2service as well, but it did not work.

Transition does not work

Hi,

I imported "Transtion" in the file header.

import { D3Service, D3, D3DragEvent, D3ZoomEvent, Selection, Transition } from 'd3-ng2-service';

and I called transtion function in below codes, and this is no error for syntax checking inside vscode.

           var data = this.d3G
          .selectAll("undrawedDies")
           .data(this._arrDies);

           data.enter()
           .append("rect")
          .attr("x", function (d, i) {return d.xCoord * d.xWidth - 1;})
           .attr("y", function (d, i) {return d.yCoord * d.yHeight - 1;})
           .attr("width", function (d) {return d.xWidth-1; })
           .attr("height", function (d) {return d.yHeight-1; })

           data.transition().duration(800)
          .attr("fill", function (d) {return d.fillColor});

but when I use angluar-cli to compiled codes, it tell me:

ERROR in E:/opensource-project/temp-aspnet/angularcli/d3-ng2-demo-master/src/app/d3-demos/wafer-map/wafer-map.component.ts (231,12): Property 'transit
ion'
does not exist on type 'Selection<BaseType, DieRect, SVGGElement, any>'.
webpack: Failed to compile.

what's wrong with my codes?
thank you!

Installation instructions? SystemJS config?

Hi there,

I'm using gulp and systemjs to load libraries into angular 2. There's no information on the README about how to load this library without using ng serve. Right now the import statement fails:

import {
D3Service,
D3,
Axis,
BrushBehavior,
BrushSelection,
D3BrushEvent,
ScaleLinear,
ScaleOrdinal,
Selection,
Transition
} from 'd3-ng2-service';

I'm presuming it's because you're importing d3 from ./bundle-d3 and that fails to load because my libraries are in /static/libs/d3/, so then it throws an 'Unexpected token' error because it's failing to find the things you're referencing in the d3.service.js?

Roadmap for D3 Service

This issue was opened as a forum to post/discuss ideas for enhancing the D3 Service for Angular 2.

Consideration to enhancements will be given to enhancements/changes which will retain a to be finalized reasonable project scope.

Example considerations are:

  • It may be very sensible to package the service into an Angular 2 modules as opposed to simply providing the service.
  • It could be worthwhile to add some custom type guards.

The scope and the resulting roadmap should, however, likely not extend to include e.g. D3 Components.

Fails when use systemjs.config.js

I am getting error zone.js:1274 GET http://localhost:3000/traceur 404 (Not Found) when add d3-ng2-service in systemjs.config.js

Steps to reproduce:

  1. Use https://angular.io/docs/ts/latest/quickstart.html example.
  2. Install d3-ng-service.
  3. Update AppModule and add TestD3Component.
  4. Check result:
    Expected result: All components are displayed without errors;
    Actual result: Getting error 404.

I use the following systemjs.config.js:

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/',
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                       'npm:rxjs',
      'angular2-in-memory-web-api': 'npm:angular2-in-memory-web-api',
      'd3-ng2-service': 'npm:d3-ng2-service',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      'angular2-in-memory-web-api': {
        main: './index.js',
        defaultExtension: 'js'
      },
      'd3-ng2-service': {
        main: './index.js',
        defaultExtension: 'js'
      },
    }
  });
})(this);

Question: what does this service provide that you do not get by simply importing d3 directly?

I've been able to use d3 in my Angular 2 Typescript application created using angular-cli by adding this to my package.json in the dependencies section:

"d3": "^4.4.0"

and this to my package.json in the devDependencies section:

"@types/d3": "^4.4.0"

and then using these imports in my TS files:


import * as d3 from 'd3';
import {
    Selection,
    Axis,
    ScaleLinear
} from 'd3'; // I am using these imports to get specific types 

So what does this d3-ng2-service give me that I am not already getting from just using d3 directly?

d3.tsv not working

I'm having trouble using d3.tsv after import the D3Service and was wondering if anyone else was experiencing similar problems? I was able to get Mike Bostock's tutorial working up until using the d3.tsv function for loading in external data from a file. (https://bost.ocks.org/mike/bar/2/)

Am I missing a module import? (I've included D3Service, D3, and Selection in my chart component.

'this' element

Hi,
I would like to be able to access the a d3 element's 'this' within an 'each()' function.

d3.selectAll(".txt").each(() => { d3.select(this) })

However, the 'this' element that I receive is the component's 'this' element. I see in one of your demos that you have used an external function, such as:

function helper(this: SVGTextElement) { d3.select(this); }

However, I'm wondering if there is a way to operate on 'this' within the 'each' function.

d3.tsv, d3.csv, d3.dsv return error

d3.tsv, d3.csv, d3.dsv returns error

Steps to reproduce:

  1. Add console.log to drag-zoom-2.component.ts in d3-ng2-demo project:
ngOnInit() {
    let d3 = this.d3;
    console.log('d3.csv:', d3.dsv);
    console.log('d3.csv:', d3.csv);
    console.log('d3.csv:', d3.tsv);
    let d3ParentElement: Selection<HTMLElement, any, null, undefined>;
    //.....
  1. Start local server:
npm run start

Expected result: Application is loaded successfully without errors. Code of dsv,csv,tsv methods displayed.
Actual result: Application is loaded with errors below:

client?93b6:76[default] /Users/vcernomschi/d3-ng2-demo/src/app/d3-demos/drag-zoom-2/drag-zoom-2.component.ts:59:30 
Property 'dsv' does not exist on type 'typeof "/Users/vcernomschi/d3-ng2-demo/node_modules/d3-ng2-service/src/bundle-d3"'.errors @ client?93b6:76
client?93b6:76[default] /Users/vcernomschi/d3-ng2-demo/src/app/d3-demos/drag-zoom-2/drag-zoom-2.component.ts:60:30 
Property 'csv' does not exist on type 'typeof "/Users/vcernomschi/d3-ng2-demo/node_modules/d3-ng2-service/src/bundle-d3"'.errors @ client?93b6:76
client?93b6:76[default] /Users/vcernomschi/d3-ng2-demo/src/app/d3-demos/drag-zoom-2/drag-zoom-2.component.ts:61:30 
Property 'tsv' does not exist on type 'typeof "/Users/vcernomschi/d3-ng2-demo/node_modules/d3-ng2-service/src/bundle-d3"'. 

Missing CurveFactory Type

I would like to select curve interpolation by attribute <svg:path my-curve-directive interpolate="sabertooth" ..>..

import {
  D3,
  D3Service,
  Line,
  ScaleLinear,
  ScaleTime,
  Selection,
  Path,
  CurveFactory // <- missing
} from 'd3-ng2-service';


interface IRealtimeGraphData {
  time: number;
  value: number;
}

interface IInterpolationMap {
  [name: string]:  Function // should be: CurveFactory,
}

@Directive({
  selector: 'my-curve-directive'
})
export class ComposableCurveDirective implements OnInit {
  private d3: D3;
  private parentNativeElement: any;
  // private d3Svg: Selection<SVGSVGElement, any, null, undefined>;
  private d3G: Selection<SVGGElement, any, null, undefined>;

  protected line: Line<IRealtimeGraphData>;
  protected path: Path | Selection<SVGGElement, any, null, undefined>; // another problem here..

  // [..]

  @Input() interpolate = 'sabertooth';
  protected interpolations: IInterpolationMap = {};

  constructor( element: ElementRef, d3Service: D3Service ) {
    this.d3 = d3Service.getD3();
    this.parentNativeElement = element.nativeElement;
    this.interpolations['sabertooth'] = this.d3.curveStepBefore;
    // TODO add more interpolations
  }

//...
}

How can I access the CurveFactory Type? It's there but I can't import it..

TS2345: Argument of type 'Function' is not assignable to parameter of type 'CurveFactory | CurveFactoryLineOnly'. Type 'Function' is not assignable to type 'CurveFactoryLineOnly'. Type 'Function' provides no match for the signature '(context: Path | CanvasRenderingContext2D): CurveGeneratorLineOnly'

Update service dependencies to D3 v 4.4

Need to update d3-zoom dependency to 1.1

  • Update dependencies
  • Update interface exports
  • Release new version of service.

EDIT: Change, only d3-zoom needs to be updated. d3-geo is already current.

Unable to load transpiler to transpile .../d3-ng2-service/index.js

When using systemjs to load the app, I'm getting the following issue:

services:35 Error: (SystemJS) Unexpected token <
    SyntaxError: Unexpected token <
    Evaluating http://localhost:8081/traceur
    Error loading http://localhost:8081/traceur
    **Unable to load transpiler to transpile http://localhost:8081/node_modules/d3-ng2-service/index.js**
    Error loading http://localhost:8081/node_modules/d3-ng2-service/index.js as "d3-ng2-service" from http://localhost:8081/app/core/core.module.js

This is the content of the d3-ng2-service/index.js HTTP response:

export * from './src/d3.service';
//# sourceMappingURL=index.js.map

In the live-example there is no loader, so it doesn't show how to configure a loader to use the d3-ng2-service. Do you have an example of that? I'd like to see the lib working with a loader to check what am I doing wrong.

This is my systemjs config:

...
paths: {
          'npm:': 'node_modules/'
        },
map: {
          ....
          'd3-ng2-service': 'npm:d3-ng2-service/index.js',
          .....
       }
...

thanks!

Bubble Chart Pack Layout

I am unable to make bubble chart using ng2-d3-service.`

{

let width: number;
let height: number;
let d3ParentElement: Selection<HTMLElement, any, null, undefined>;
let d3Svg: Selection<SVGSVGElement, any, null, undefined>;
var diameter = 600;
var dataset = [
{Name= "CROWN",
Count= 2
}, {
Name: "KING",
Count: 2
}, {
Name: "QUEEN",
Count: 1
}, {
Name: "CINDERELLA",
Count: 2
}, {
Name: "PRINCE",
Count: 3
}, {
Name: "PRINCESS",
Count: 1
}, {
Name: "WAND",
Count: 5
}];

var color = d3.scaleOrdinal(d3.schemeCategory20);
var bubble = d3.pack()
.size([diameter, diameter])
.padding(1);

if (this.parentNativeElement !== null) {
d3ParentElement = d3.select(this.parentNativeElement);
var d3Svgdemo = d3ParentElement.select(".chart").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.attr("class", "bubble");
var nodes = d3.hierarchy(dataset)
.sum(function(d: any) { return d.Count; });

var node = d3Svgdemo.selectAll(".node")
.data(bubble(nodes).descendants())
.enter()
.filter(function(d){
return !d.children
})
.append("g")
.attr("class", "node")
.attr("transform", function(d) {
console.log(d.x + "" + d.y)
return "translate(" + d.x + "," + d.y + ")";
});

node.append("title")
.text(function(d:any) {
return d.data.Name + ": " + d.data.Count;
});

node.append("circle")
.attr("r", function(d) {
return d.r;
})
.style("fill", function(d:any) {
return color(d.data.Name);
});

node.append("text")
.attr("dy", ".3em")
.style("text-anchor", "middle")
.text(function(d:any) {
return d.data.Name.substring(0, d.r / 3) + ": " + d.data.Count;
});
}

Getting d3.event

I'm not using this lib, but I use a similar enough code that you will get the same problem: when importing * from d3-selection, then it will export a constant d3.event value.
This value is never updated by new events.

I'm not sure if this is a problem with es6 imports or just webpack...

The trick that I use for angular 2, adding a getter for event on the service that uses require to get a "fresh" event everytime I need it:

get event() {
  return require("d3-selection").event;
}

Then in your code call d3Service.event to get the event, instead of d3.event

Appending a g element to SVGSVGElement returns BaseType instead of SVGGElement

Using D3Service from d3-ng2-service, I am doing the following:

export class TimelineComponent implements OnDestroy, OnInit {
    private d3: D3;
    private htmlElement: HTMLElement; // HTML <timeline> element
    private d3ParentElement: Selection<HTMLElement, any, null, undefined>; 
    private d3Svg: Selection<SVGSVGElement, any, null, undefined>;  // d3.select('svg')
    private d3G: Selection<SVGGElement, any, null, undefined>;  // d3.select('g') child of svg
    private margin: {top: number, right: number, bottom: number, left: number};   
    private width: number;       // Component width
    private height: number;      // Component height
    private colorScale: ScaleOrdinal<number, string>;

    constructor(private element: ElementRef, d3Service: D3Service) {
        this.d3 = d3Service.getD3();
        this.htmlElement = element.nativeElement;
    }

    ngOnInit() {
        this.d3ParentElement = this.d3.select(this.htmlElement);
        this.d3Svg = this.d3ParentElement.select<SVGSVGElement>('svg');
        this.setup();
        this.buildContainer();
    }

    private setup() {
        this.margin = { top: 10, right: 10, bottom: 10, left: 10 };
        this.width = this.htmlElement.firstElementChild.clientWidth - this.margin.left - this.margin.right;
        this.height = this.width * 0.5 - this.margin.top - this.margin.bottom;
    }

    buildContainer() {
      this.d3Svg = this.d3Svg
        .attr('width', this.width + this.margin.left + this.margin.right)
        .attr('height', this.height + this.margin.top + this.margin.bottom);
      this.d3G = this.d3Svg
        .append('g')
        .attr('transform', 'translate(' + this.margin.left + ',' + this.margin.top + ')')
        .attr('class', 'container');
     }
}

This throws a TypeScript error:

error TS2322: Type 'Selection<BaseType, any, null, undefined>' is not 
assignable to type 'Selection<SVGGElement, any, null, undefined>'.
 Type 'BaseType' is not assignable to type 'SVGGElement'.
Type 'Element' is not assignable to type 'SVGGElement'.
  Property 'farthestViewportElement' is missing in type 'Element'.

Is this an error in the D3Service Types or am I selecting/appending incorrectly?

Bubble Chart

I am unable to make bubble chart using ng2-d3-service.`

{

let width: number;
let height: number;
let d3ParentElement: Selection<HTMLElement, any, null, undefined>;
let d3Svg: Selection<SVGSVGElement, any, null, undefined>;
var diameter = 600;
var dataset = [
     {Name= "CROWN",
     Count= 2
      }, {
         Name: "KING",
          Count: 2
      }, {
          Name: "QUEEN",
          Count: 1
      }, {
          Name: "CINDERELLA",
          Count: 2
      }, {
          Name: "PRINCE",
          Count: 3
      }, {
          Name: "PRINCESS",
          Count: 1
      }, {
          Name: "WAND",
          Count: 5
      }];

var color = d3.scaleOrdinal(d3.schemeCategory20);
var bubble = d3.pack()
        .size([diameter, diameter])
        .padding(1);

if (this.parentNativeElement !== null) {
  d3ParentElement = d3.select(this.parentNativeElement);
  var d3Svgdemo = d3ParentElement.select(".chart").append("svg")
        .attr("width", diameter)
        .attr("height", diameter)
        .attr("class", "bubble");
        var nodes = d3.hierarchy(dataset)
        .sum(function(d: any) { return d.Count; });

var node = d3Svgdemo.selectAll(".node")
        .data(bubble(nodes).descendants())
        .enter()
        .filter(function(d){
            return  !d.children
        })
        .append("g")
        .attr("class", "node")
        .attr("transform", function(d) {
          console.log(d.x + "" + d.y)
            return "translate(" + d.x + "," + d.y + ")";
        });

node.append("title")
        .text(function(d:any) {
            return d.data.Name + ": " + d.data.Count;
        });

node.append("circle")
        .attr("r", function(d) {
            return d.r;
        })
        .style("fill", function(d:any) {
            return color(d.data.Name);
        });

node.append("text")
        .attr("dy", ".3em")
        .style("text-anchor", "middle")
        .text(function(d:any) {
            return d.data.Name.substring(0, d.r / 3) + ": " + d.data.Count;
        });

}

Dendrogram link/arc issue

Hi Tim,
Great service ! you're examples worked out of the box :-)
I'm trying to implement the D4 version of a cluster dendrogram (http://bl.ocks.org/mbostock/4063570).
However, I'm running into a problem which most likely isn't related to the service but I'm hoping you can help.
In my implementation, the links between nodes are filled on.
I've attached the source and screen shot of the issue.
Hope you can shed some light on this.
Dave
capture1
d3Component.txt

how would I update a component variable in callback?

I'm trying to update an ng2 component variable from my mouseOver callback, but I can't seem to update any member variables in my component
var enter = svg.enter() .append("circle") .attr("r", 10) .on("mouseover", _mouseOver) .on("mouseout",_mouseOut)

Getting error when adding `d3-ng2-service` with webpack for angular2

Getting error when importing d3-ng2-service with webpack for angular2.

Steps to reproduce.

  1. Create project based on https://angular.io/docs/ts/latest/guide/webpack.html.
  2. Add d3-ng2-service based on https://www.npmjs.com/package/d3-ng2-service.
  3. Add d3 chart sample from https://github.com/tomwanzek/d3-ng2-demo to check if it works.
    Expected result: Chart is displayed without errors;
    Actual result: Chart is not displayed. The following error is displayed in d3-ng2-service/index.js :
index.js: Uncaught SyntaxError: Unexpected token export

Just wonder if there are need any additional settings to webpack which I need to add to get it working. It looks like currently it doesn't support es6 keyword. But we have the same imports in polyfills.ts as in d3-ng2-demo.

Please refer to repo: https://github.com/vcernomschi/ng2-d3-webpack

If you comment out the below statements:
1 - importing d3-ng2-service and declarationBrushZoom2Component in root module src/app/module/app.module.ts
2 - exporting export * from './d3-demos/brush-zoom-2/brush-zoom-2.component'; insrc/app/components/reports/index.js
you will get it working without d3-ng2-service;

Thanks in advance.

Update d3-geo to 1.3.1:

  • update dependencies for module
  • update definitions dependency
  • Review barrel to ensure completeness with respect to new exports

Fails when use systemjs.config.js

My issue is similar to #11

Just so you know, I am using UMD packages, and still see the problem.

I am attaching package.json, app module and systemjs. I highly appreciate your help!

Given below is error I get :

diagnostic:19 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/traceur
Error: XHR error (404 Not Found) loading http://localhost:3000/traceur
at XMLHttpRequest.wrapFn [as _onreadystatechange] (https://unpkg.com/[email protected]?main=browser:647:29)
at ZoneDelegate.invokeTask (https://unpkg.com/[email protected]?main=browser:236:37)
at Zone.runTask (https://unpkg.com/[email protected]?main=browser:136:47)
at XMLHttpRequest.ZoneTask.invoke (https://unpkg.com/[email protected]?main=browser:304:33)
Error loading http://localhost:3000/traceur
Unable to load transpiler to transpile http://localhost:3000/node_modules/d3-ng2-service/index.js

Archive.zip

build failing while running the project

94% asset optimizationError in bail mode: [default] /Users/kodiraj/Documents/workspace/future/src/main/webapp/ui/nextgenportal/node_modules/@types/geojson/index.d.ts:21:16
Duplicate identifier 'Position'.

base.json references missing file: index.ts

d3-ng2-service\configs\base.json has a reference to "../index.ts", which does not exist.
Was it supposed to be index.d.ts instead?

VS Code complains about it:

file: 'file:///c%3A/xxxx/node_modules/d3-ng2-service/tsconfig.json'
severity: 'Error'
message: 'File 'c:/xxxx/node_modules/d3-ng2-service/configs/../index.ts' not found.'
at: '1,1'
source: 'ts'

Rename project to d3-ngx-service?

Hi there! Love the project. I am opening this merely because someone opened an equivalent issue on my library and I think it seems like a reasonable change that i hope may catch on.

Anyway, if you disagree or do not want to deal with the headache of a rename I completely understand and please feel free to close this issue.

Regards,
Andy

Property 'json' doesn't exist on type 'd3'

I'm trying to implement d3 example http://bl.ocks.org/mbostock/4062045 using d3-ng2-service. I got d3 instance by this.d3 = d3Service.getD3(); and then I try to call d3.json() function
this.d3.json("miserables.json", function(error, graph){});
In this case compiler throws error "Property 'json' doesn't exist on type 'd3'"
"d3-ng2-service": "1.5.3",

What is the proper way to resolve this?

not accessible methods

I imported the library as told in the Readme. However, I can't access e.g. this.d3.csv(filename, ...) or this.d3.request(filename).
The error I am getting is:

TS2339: Property 'csv' does not exist on type 'typeof "[path]/d3-ng2-servi...'.

My import in the component file is: import { D3Service, D3, Selection } from 'd3-ng2-service'; am I missing imports to be able to use this?
Calling this.d3.range(300); works.

I found #13 but it didn't help me.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.