D3 v5:未为折线图绘制线,并且在y轴上未显示刻度线

时间:2020-05-05 02:37:04

标签: d3.js

更新,这是控制台中的错误消息: 错误:属性d:预期数字“ M0,NaNL21.654801022…”。

我确信这是一个相当简单的d3问题,并且我查看了其他答案,但似乎没有任何帮助,刻度线未显示在y轴上,但它们在x轴上运行良好。此外,这应该是折线图,但未画线。

这是代码:

var margin = {top: 10, right: 40, bottom: 150, left: 70},
width = 760 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom; 

var w = width + margin.left + margin.right;
var h = height + margin.top + margin.bottom;

var svg = d3.select("body").append("svg") // this appends a new SVG element to body
    .attr("width", w) // set the width 
    .attr("height", h) // set the height
    .append("g") 
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// x scale will handle time
var xScale = d3.scaleTime().range([0,width]);

// y scale will handle energy consumption values
var yScale = d3.scaleLinear().range([height,0]);

// Define X and Y AXIS
var yAxis = d3.axisLeft(yScale);
var xAxis = d3.axisBottom(xScale); 

var parseTime = d3.timeParse("%Y"); 


function rowConverter(data) {
    return {
        year : parseTime(data.year),
        value : +data.average // the + operator parses strings into numbers
    };
}

// line generator function
var line = d3.line()
    .curve(d3.curveBasis)
    .x(function(d) { return xScale(d.year); })
    .y(function(d) { return yScale(d.average); })


d3.csv("moreDummyData.csv",rowConverter).then(function(data){


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

xScale.domain(d3.extent(data, function(d) { return d.year; })); 


// Draw xAxis
svg.append("g") // add a new svg group element
    .attr("class", "x axis")
    .attr("transform", "translate(0, " + height + ")")
    .call(xAxis)
    .selectAll("text")
    .attr("dx", "-.8em")
    .attr("dy", ".25em")
    .attr("text-anchor", "end");

// Draw yAxis
svg.append("g")
    .attr("class", "y axis")
    .call(yAxis)
    .selectAll("text")
    .attr("dx", "-.8em")
    .attr("dy", ".25em")
    .attr("text-anchor", "end");

// add a title for the yAxis
svg.append("text") // add a new svg "text" element
    .attr("text-anchor", "end")
    .attr("transform", "rotate(-90)") // turn it on its side
    // position the title in space
    .attr("y", -margin.left+20) 
    .attr("x", -margin.top-75)
    // give it text and style
    .text("ADD TITLE")
    .attr("font-family", "Times")
    .attr("font-size", "16px"); 

    svg.append("path")
    .datum(data)
    .attr("class", "line")
    .attr("d", line);
}); 

这是此代码的输出结果:

code output

数据如下:

年,平均

1971,30

1972,34

1973,29

1974,28

1975,31

1976,35

0 个答案:

没有答案