我有一个Flask网络服务器,它接受Python数据的字典,并在/data
上调用GET时使用jsonify函数返回JSON对象。 JSON对象不是嵌套列表(参见下面的示例),就像这里的大多数其他示例一样。
我一直在尝试获取JSON数据并将其传递给我的d3.svg.line()
函数,但似乎我传入的数据出了问题。我的网页呈现轴,但没有显示任何行。
检查元素显示x和y轴填充了我的数据(<path class="domain" d="M0,6V0H890V6"></path>
),但我的<path class="line"></path>
为空。
我正在运行一个map函数将我的日期和值转换为正确的格式并将它们作为数组返回。在此函数上运行console.log
会显示有效JSON对象的输出。
有人可以帮助我解决我在这里出错的地方吗?我应该将我的jsonified对象重新格式化为嵌套列表,然后使用forEach
填充我的数据对象吗?
以下是我的代码和JSON示例:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body { font: 12px Arial; }
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
var x = d3.time.scale().range([0,width]);
var y = d3.scale.linear().range([height,0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var valueline = d3.svg.line()
.x(function(d) {return x(d.timeStamps); })
.y(function(d) {return y(d.outTemps); });
var svg = d3.select("body")
.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 + ")");
d3.json("/data",function(error, data) {
function type(d) {
d.timeStamps =
d.timeStamps.map(function (time) {return formatDate(time) } );
d.outTemps = d.outTemps.map(function (temp) {return parseFloat(temp)});
};
x.domain(d3.extent(data, function (d) {return d.timeStamps}));
y.domain(d3.extent(data, function(d) { return d.outTemps; }));
svg.append("path")
.datum(data)
.append("path")
.attr("class", "line")
.attr("d", valueline(data));
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
});
</script>
</body>
{
"outTemps": [
"79.7",
"79.7",
"79.8",
],
"timeStamps": [
"2016-09-20 19:15:07",
"2016-09-20 19:10:07",
"2016-09-20 19:05:11",
]
答案 0 :(得分:0)
d3
您的数据格式奇怪。 d3
更喜欢对象数组,其中对象的每个属性代表x
或y
。因此,正确格式化的数据应如下所示:
[{
"timeStamps": "2016-09-20T23:15:07.000Z",
"outTemps": 79.7
}, {
"timeStamps": "2016-09-20T23:10:07.000Z",
"outTemps": 79.7
}, {
"timeStamps": "2016-09-20T23:05:11.000Z",
"outTemps": 79.8
}]
此外,我的猜测是您的type
功能是尝试重新格式化数据,但您甚至不会调用它...
最后,如果您只想使用JavaScript重新格式化数据,它看起来像这样:
data = data.timeStamps.map(function(d, i) {
return {
timeStamps: formatDate(d),
outTemps: parseFloat(data.outTemps[i])
}
});