Vishnu Suresh
Vishnu Suresh

Reputation: 187

Create a pie chart with TypeScript and D3

I'm trying to create a pie chart using typescript and d3 with static data. But I'm just getting a blank screen.Can someone help? I'm new to both d3 and typescript.

There's no tsconfig.json file. I simply compile the .ts file using tsc command and link the corresponding .js file to the HTML.

Here's the typescript code:

 interface Data {
            quantity: number;
            category: string;
        }


 let testData: Data[] = [
        {
            quantity: 10,
            category: 'a'
        },
        {
            quantity: 20,
            category: 'b'
        },
        {
            quantity: 10,
            category: 'c'
        },
        {
            quantity: 100,
            category: 'd'
        },
        {
            quantity: 500,
            category: 'e'
        }
    ];

drawChart(testData);

function drawChart(data: Data[]) {

    let width = 400,
        height = 400,
        radius = Math.min(width, height) / 2,
        colourValues = d3.scale.category20c();

    let arc = d3.svg.arc<d3.layout.pie.Arc<Data>>()
        .innerRadius(radius - 70)
        .outerRadius(radius - 0);

    let pie = d3.layout.pie<Data>().value((d: Data):number => d.quantity);


    let fill = (d: d3.layout.pie.Arc<Data>): string => colourValues(d.data.category);
    let tf  = (d: d3.layout.pie.Arc<Data>): string => `translate(${arc.centroid(d)})`;
    let text = (d: d3.layout.pie.Arc<Data>): string => d.data.category;

    let svg = d3.select('.pie-chart').append('svg')
        .attr('width', width)
        .attr('height', height)
        .append('g')
        .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');

    let g = svg.selectAll('.arc')
        .data(pie(data))
        .enter().append('g').attr('class', 'arc');   
    g.append('path').attr('d', arc).attr('fill', fill);   
    g.append('text').attr('transform', tf).text(text);
}

Here's my HTML :

<head>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script src="piechart1.js"></script>    
</head>
<body>
    <div class="pie-chart"></div>
</body>

Upvotes: 1

Views: 4871

Answers (1)

Fenton
Fenton

Reputation: 250882

You are calling the function before the element exists... if you move the scripts the order of execution should be better:

<head>
</head>
<body>
    <div class="pie-chart"></div>
    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script src="piechart1.js"></script>    
</body>

Upvotes: 2

Related Questions