我尝试使用数组中的数据创建D3折线图。我从数据库中获取数据,但我似乎无法填充路径行。我在控制台上没有任何错误,所以我对我做错了什么感到有些困惑。我还是D3新手。
这是我的代码:
//set dimensions
var margin = {top:30, right:20, bottom:30, left:50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
//parse date/time
var parseDate = d3.time.format("%Y-%b-%d").parse;
//set ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
//define axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(10);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(10);
//define the line
var volumesLine = d3.svg.line()
.x(function(d) {return x(parseDate(d.MonthStartDate));})
.y(function(d) {return y(d.Volumes);});
//get data from database
var data = {MonthStartDate: [errorData[1]["MonthStartDate"]], Volumes: [errorData[1]["Volume"]], VolumeId: [errorData[1]["VolumeId"]]};
console.log(data);
//nest data by volume id
data = d3.nest()
.key(function(d){ return d.VolumeId; })
.entries(data);
data.forEach(function(d) {
svg.append("path")
.attr("class", "line")
.attr("d", volumesLine(d.values));
});
x.domain(d3.extent(data, function(d){ return d.MonthStartDate; }));
y.domain([0, d3.max(data, function(d){ return d.Volumes; })]);
//add the svg to canvas
var svg = d3.select("#volumeChart")
//.datum(data)
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
//add the Y Axis
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
//create path
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", volumesLine);