如果这似乎是一个重复的D3问题,请道歉。我花了两天时间试图弄清楚如何做到这一点。
我正在尝试创建一个多线图表,其中x轴为序数刻度,y轴为正常线性刻度。
从外部JSON加载数据:
[
{
"arbeitsgang":"A1",
"y":5,
"z":4
},
{
"arbeitsgang":"A2",
"y":6,
"z":11
},
{
"arbeitsgang":"A3",
"y":4,
"z":45
}
]
以下是我为尝试制作图表所写的内容:
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
body { font: 12px Arial;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.js"> </script>
<script>
var margin = {
top: 20,
right: 20,
bottom: 20,
left: 50
},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var x = d3.scale.ordinal().rangeRoundBands([0, width],0.1);
var y = d3.scale.linear().rangeRound([height, 0]);
var ordinalScale = d3.scale.ordinal();
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
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 + ")");
var line = d3.svg.line()
.x(function(d) { return x(d.arbeitsgang); })
.y(function(d) { return y(d.koordinaten); });
d3.json("Arbeitsgang.json", function(error, data) {
ordinalScale.domain(d3.keys(data[0]).filter(function(key) { return key !== "arbeitsgang"; }));
data.forEach(function(d) {
d.arbeitsgang = d.arbeitsgang;
d.y = +d.y;
d.z = +d.z;
});
var arbeitsgange = ordinalScale.domain().map(function(name) {
return {
name: name,
values: data.map(function (d) {
return {arbeitsgang: d.arbeitsgang, koordinaten: +d[name]};
})
}
});
x.domain(d3.extent(data, function(d) { return d.arbeitsgang; }));
y.domain([
d3.min(arbeitsgange, function(c) { return d3.min(c.values, function(v) { return v.koordinaten; }); }),
d3.max(arbeitsgange, function(c) { return d3.max(c.values, function(v) { return v.koordinaten; }); })
]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var graphen = svg.selectAll(".graphen")
.data(arbeitsgange)
.enter().append("g")
.attr("class", "graphen");
graphen.forEach(function(d) {
console.log(d);
});
graphen.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values)});
});
</script>
</body>
所以似乎有两个错误: 1. x轴只有2个刻度(A1,A3),但缺少A2 2.没有图表可见。 使用html dom profiler,您可以看到有2个图表:
<path class="line" d="M26,254LNaN,247L278,260"/>
<path class="line" d="M26,260LNaN,216L278,0"/>
正如您所看到的,内部存在NaN。解析时可能是错误。我根本就不知道。
感谢您的帮助