简体   繁体   中英

Trendline not appearing on timeseries graph using d3.js

I am new to using d3.js and am trying to plot a timeseries graph with a trendline. The axes are showing correctly, but I am uncertain why the trendline is not appearing. What should I change in my code to make the trendline appear? I am using d3 v4.

//create function to parse the date
var parseDate = d3.timeParse("%m/%d/%Y");

//open the dataset

d3.csv("filename.csv", function(error, data) {
data.forEach(function(d){
    //parse the date
    d.date = parseDate(d.date);
    d.value = +d.value
})
visualize(data)
});


//set up SVG
var width = 1500;
var height = 800;
var padding = 30;


function visualize(dataset) {
//set ranges
var xScale = d3.scaleTime().range([padding,width-padding]);
var yScale = d3.scaleLinear().range([height-padding,padding]);

//define line
var trendline = d3.line()
                    .x(function(d) {return d.date})
                    .y(function(d) {return d.value});

//create svg element
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var g = svg.append("g")
.attr("transform", "translate(" + padding + "," + padding + ")");

//scale the range of the data
xScale.domain(d3.extent(dataset, function(d) {return d.date}))
yScale.domain([0,d3.max(dataset, function(d) {return d.value;})])


g.append("g")
    .attr("transform","translate("+ padding +"," + (height-padding*2) + ")")
    .call(d3.axisBottom(xScale).ticks(10));

g.append("g")
    .attr("transform","translate("+padding*2+",0)")
    .call(d3.axisLeft(yScale));

g.append("path")
    .data(dataset)
    .attr("fill", "none")
    .attr("stroke", "steelblue")
    .attr("stroke-linejoin", "round")
    .attr("stroke-linecap", "round")
    .attr("stroke-width", 1.5)
    .attr("d", trendline);
}

Right now your line generator...

var trendline = d3.line()
    .x(function(d) {return d.date})
    .y(function(d) {return d.value});

... uses the values in the dataset as they are. This is clearly incorrect, since you have dates for the x value (according to your scale).

The solution is simple, just use your scales in the line generator:

var trendline = d3.line()
    .x(function(d) {return xScale(d.date)})
    .y(function(d) {return yScale(d.value)});

Also, use datum , not data :

g.append("path")
    .datum(dataset)
    //etc...

After applying the suggestions by @Geredo change this line

.attr("d", trendline);

with

.attr("d",trendline(data));

it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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