简体   繁体   English

使用 TypeScript 和 D3 创建饼图

[英]Create a pie chart with TypeScript and D3

I'm trying to create a pie chart using typescript and d3 with static data.我正在尝试使用带有静态数据的 typescript 和 d3 创建饼图。 But I'm just getting a blank screen.Can someone help?但我只是得到一个空白屏幕。有人可以帮忙吗? I'm new to both d3 and typescript.我是 d3 和打字稿的新手。

There's no tsconfig.json file.没有tsconfig.json文件。 I simply compile the .ts file using tsc command and link the corresponding .js file to the HTML.我只是使用tsc命令编译.ts文件并将相应的.js文件链接到 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 :这是我的 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>

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>

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

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