简体   繁体   English

JavaScript d3 带纵轴和 json 数据的折线图

[英]JavaScript d3 line graph with ordinal axis and json data

I am new creating charts with d3 and Im trying to build a line chart with ordinal axis.我是使用 d3 创建图表的新手,我正在尝试使用序数轴构建折线图。 I have managed to visualize the y axis and the x axis correctly, but I am not able to create the line.我已经成功地可视化了 y 轴和 x 轴,但我无法创建线。

I have this code:我有这个代码:

    var margin = {top: 10, right: 30, bottom: 30, left: 60},
    width = 460 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

    var data = [{
        name: "cat",
        value: 10
    }, {
        name: "dog",
        value: 3
    }, {
        name: "pig",
        value: 7
    }, {
        name: "bird",
        value: 7
    }];


    //append the svg object to the body of the page
    var svg = d3.select("#div-svg"  ).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 + ")");

    //set scale
    var xScale = d3.scaleBand()
            .domain(d3.extent(data, function(d){return d["name"]}))
            .range([0, width]),
        yScale = d3.scaleLinear()
            .domain([min(this.value_array), max(this.value_array)])
            .range([height, 0]);
       
    //add Axis
    svg.append("g")
        .attr("transform", "translate(0," + height + ")")
        .call(d3.axisBottom(xScale));

    svg.append("g")
        .call(d3.axisLeft(yScale));

Up to here everything works fine.到这里一切正常。 The next part is the onethat doesn't work.下一部分是不起作用的部分。

   //line
    var line = d3.line()
        .x(function(d) { return xScale(d[0]); }) 
        .y(function(d) { return yScale(d.value); }) 

If I put d[0] I get the following error " type number is not assignable to parameter of tye string ".如果我输入d[0]我会收到以下错误“类型号不可分配给 tye 字符串的参数”。 If I put d.name I get the following error " 'name' does not exist on type [number,number] ".如果我输入d.name我会收到以下错误“ 'name' does not exist on type [number,number] ”。 I don't know how to proceed to display the chart.我不知道如何继续显示图表。 Do you have any solution?你有什么解决办法吗?

Also I would like it to be an area chart not just a linechart, in case the procedure changes.此外,我希望它是一个面积图,而不仅仅是一个折线图,以防程序发生变化。

d3.extent is not what you want to use for the domain. d3.extent不是您要用于域的内容。 You need an array with each of the bar names.您需要一个包含每个条形名称的数组。

var xScale = d3.scaleBand()
            .domain(data.map(function(d){return d["name"]}))
            .range([0, width])

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

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