最佳答案
我只是通过向 y 轴添加另一条路径来解决这个问题:
// define how much space you'd like to create the axis "break" in
var axisBreakSpace = 50;
// Add the X Axis, with the space
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height + axisBreakSpace) + ")")
.call(xAxis);
// Add the Y Axis, normally
var yG = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
// add the zigzags path
yG.append("path")
.attr("d", function(){
var numZags = 10, // number of zigzags
zagDist = (axisBreakSpace - 5) / numZags; // y distance on each zig or zag, -5 is a bit of space to finish it off
// build the path at
var curZig = height,
d = "M0," + curZig;
for (var i = 0; i < numZags; i++){
curZig += zagDist;
d += (i % 2 === 0) ? " L10," + curZig : " L-10," + curZig;
}
// finish it off to the x-axis
d += " L0," + (height + axisBreakSpace);
return d;
});
完整的工作代码示例:
<!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: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
</style>
<body>
<!-- load the d3.js library -->
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
// Set the dimensions of the canvas / graph
var margin = {
top: 30,
right: 20,
bottom: 100,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom,
axisBreakSpace = 50;
// Set the ranges
var x = d3.scale.linear().range([0, width])
.domain([0, 10]);
var y = d3.scale.linear().range([height, 0])
.domain([200,1000]);
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom")
var yAxis = d3.svg.axis().scale(y)
.orient("left");
// Define the line
var line = d3.svg.line()
.x(function(d) {
return x(d.x);
})
.y(function(d) {
return y(d.y);
});
// Adds the svg canvas
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 data = d3.range(10).map(function(d){
return {
x: d,
y: (Math.random() * 800) + 200
}
});
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", line(data));
// Add the X Axis
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height + axisBreakSpace) + ")")
.call(xAxis);
// Add the Y Axis
var yG = svg.append("g")
.attr("class", "y axis")
.call(yAxis);
yG.append("path")
.attr("d", function(){
var numZags = 10,
zagDist = (axisBreakSpace - 5) / numZags;
var curZig = height,
d = "M0," + curZig;
for (var i = 0; i < numZags; i++){
curZig += zagDist;
d += (i % 2 === 0) ? " L10," + curZig : " L-10," + curZig;
}
d += " L0," + (height + axisBreakSpace);
return d;
});
</script>
</body>
关于D3.JS:y 轴上零和起始值之间的之字形线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34811041/