我一直在搜索大量帖子和教程,试图找出 d3,我想我已经弄清楚了大部分内容,但这并没有划清界限,我也不知道为什么。这是一个简单的 d3.line()
图表。数据必须转换为适合 .line()
的格式,而且确实如此。我还在控制台中确认该数据的格式为
[{time: 1881, temp: -10} , {time: 1882, temp: -9 } ...]
如果有人能帮助我解决这个问题,我将不胜感激。还有 efor d3 v4 有什么好的教程吗?
var width = 500;
var height = 500;
var margin = 25;
var axisLength = width - 2 * margin;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.style("border", "1px solid");
// 5. X scale will use the index of our data
var xScale = d3.scaleTime()
.domain(d3.extent([new Date(1881,0,1),new Date(2015,0,1)]))
.range([0, width]); // output
// 6. Y scale will use the randomly generate number
var yScale = d3.scaleLinear()
.domain(d3.extent(tempArrMap["Glob"], function(d) {return d;}))
.range([height, 0]); // output
var xAxis = d3.axisBottom(xScale);
var yAxis = d3.axisLeft(yScale);
svg.append("g")
.classed("x-axis", true)
.attr("transform", function() {
return "translate(" + margin + "," + (height - margin) + ")";
})
.call(xAxis);
var yrsCol = getCol(tempData,0)
var globCol = getCol(tempData,1);
var LineData = { x:yrsCol, y:globCol};
function fn(data){
var out = data.y.map(function (_, idx) {
return { time: data.x[idx], temp: data.y[idx] };
});
return out;
}
svg.append("g")
.classed("y-axis", true)
.attr("transform", function() {
return "translate(" + margin + "," + margin + ")";
})
.call(yAxis);
var inLineData = fn(LineData);
inLineData
现在采用适合 d3.line()
的形式,它是形式中的对象数组。我已通过控制台确认数据的有效性。
[{时间:1881,温度:-10},{时间:1882,温度:-9} ...]
var line = d3.line()
.x(function(d) { return xScale(d.time); })
.y(function(d) { return yScale(d.temp); });
svg.append("path")
.attr("d", line(inLineData))
.attr("fill", "none")
.attr("stroke", "red")
.attr("transform", function() {
return "translate(" + margin + "," + margin + ")";
});
最佳答案
在您的代码片段中,您似乎缺少 D3 生命周期方法,特别是 Enter()。
http://synthesis.sbecker.net/articles/2012/07/09/learning-d3-part-2
But lets say to begin with, we just have a blank page, with no paragraphs. How do we get new paragraphs on the page, representing the data? Enter .enter(). When we call enter() on an existing selection, we switch to a sub-selection representing the data that is yet to be mapped to an element, because there is not yet enough of them on the page to represent all of the current dataset. In other words, if there are more datums in our dataset than elements on the page, the “enter” sub-selection represents the yet-to-be-added elements.
博斯托克本人在条形图上提供了易于理解的演练。这可能有助于消除您的实现中缺失的任何令人困惑的内容。
https://bost.ocks.org/mike/bar/
又是那个讨厌的 Enter() 了。
Since we know the selection is empty, the returned update and exit selections are also empty, and we need only handle the enter selection which represents new data for which there was no existing element. We instantiate these missing elements by appending to the enter selection.
var barEnter = barUpdate.enter().append("div");
关于javascript - D3.js 只是绘制一条垂直线而不是实际绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318123/