您的示例图像中显示的图表实际上比链接的示例要容易得多;为此,您不需要创建剪切路径,也不需要用两种不同的颜色画线两次。
要绘制彩色背景,请使用使用d3.svg.area() 创建的区域路径生成器。设置 y0 访问器函数以提取数据数组中每个点的最小值,并设置 y1 访问器函数以提取最大值。
然后使用d3.svg.line() 路径生成器将线绘制为法线图。
工作示例,改编自 cmets 中的小提琴:http://jsfiddle.net/h45CD/12/
(注意:我注释掉了一半的数据集,因为“年份”值被重复,不确定应该代表什么.)
关键代码:
// Define the value line path generator
var line = d3.svg.line()
.x( function(d) { return x(d.year); } )
.y( function(d) { return y(d.temp); } );
// Define the area path generator
var area = d3.svg.area()
.x( function(d) { return x(d.year); } )
.y0( function(d) { return y(d.min); } )
.y1( function(d) { return y(d.max); } );
/* ... */
// Add the background area showing the historic range
svg.append("path")
.datum(data)
.attr("class", "historicRange")
.attr("d", area);
// Add the value line
svg.append("path")
.datum(data)
.attr("class", "dataline")
.attr("d", line);
基于 cmets 编辑
如果您确实想要一条根据历史值改变颜色的线,而不是在背景范围之上绘制的线,最直接的解决方案可能是创建一个<pattern>由不同颜色区域组成的元素,并使用它来描边值线。
您需要熟悉模式元素的不同选项。 This MDN tutorial 有一个很好的介绍,或者您可以深入了解 full W3 specs。
对于这种情况,我们希望图案的大小和位置相对于用于绘制线条的坐标系,而不考虑线条本身的大小或形状。这意味着我们将把patternUnits 和patternContentUnits 都设置为userSpaceOnUse。图案的height 和width 将是绘图区域的高度和宽度。
在图案中,我们将绘制表示最大-最小范围的区域,但我们还需要为高于最大值和低于最小值的值绘制不同颜色的单独区域。我们可以为每个使用相同的区域生成器,但每次都需要更改 y0/y1 访问器函数。
关键代码:
// Add the pattern showing the historic range
var pattern = defs.append("pattern")
.datum(data) //add the data to the <pattern> element
//so it will be inherited by each <path> we append
.attr({
"patternUnits":"userSpaceOnUse",
"patternContentUnits":"userSpaceOnUse",
"width": width,
"height": height
})
.attr("id", "strokePattern");
pattern.append("path")
.attr("class", "historicRange between")
.attr("d", area);
pattern.append("path")
.attr("class", "historicRange above")
.attr("d", area.y1( 0 )
.y0( function(d){return y(d.max);} )
);
pattern.append("path")
.attr("class", "historicRange below")
.attr("d", area.y1( function(d){return y(d.min);} )
.y0( height )
);
// Add the value line
plot.append("path")
.datum(data)
.attr("class", "dataline")
.attr("d", line)
.style("stroke", "url(#strokePattern)");
工作示例:http://jsfiddle.net/h45CD/14/