如何让我的 d3 折线图下方的区域填充为渐变?

How do I get my area filled beneath my d3 line chart to be a gradient?

我正在使用 d3 v4。我想创建一个折线图,其中图形下方的区域是由从顶部的黑暗到底部的明亮的渐变填充的区域。我认为这是配置这样的渐变的方法

  svg.append("linearGradient")
        .attr("id", "area-gradient")
        .attr("gradientUnits", "userSpaceOnUse")
        .attr("x1", 0).attr("y1", y(0))
        .attr("x2", 0).attr("y2", y(1000))
    .selectAll("stop")
        .data([
            {offset: "0%", color: "navy"},
            {offset: "30%", color: "navy"},
            {offset: "45%", color: "navy"},
            {offset: "55%", color: "navy"},
            {offset: "60%", color: "navy"},
            {offset: "100%", color: "navy"}
        ])
    .enter().append("stop")
        .attr("offset", function(d) { return d.offset; })
        .attr("stop-color", function(d) { return d.color; });

并使用这种风格

.area {                         
    fill: url(#area-gradient);                  
    stroke-width: 0px;          
}

但是正如您从我的 Fiddle -- https://jsfiddle.net/yw46ycse/3/ 中看到的那样,我拥有的是一个实心区域。我还需要做什么才能使图形下方的区域成为渐变?

有几个问题需要解决:

  1. 每一站都有 "navy",因此不会显示渐变
  2. 在这种情况下最好不要 .attr("gradientUnits", "userSpaceOnUse")。通过使用 objectBoundingBox (https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/gradientUnits) 的默认设置,您可以只使用 0,0 0,1 指定垂直线性渐变。

例如:

svg.append("linearGradient")
        .attr("id", "area-gradient")
        .attr("x1", 0).attr("y1", 0)
        .attr("x2", 0).attr("y2", 1)
    .selectAll("stop")
        .data([
            {offset: "0%", color: "navy"},
            {offset: "100%", color: "red"}
        ])
    .enter().append("stop")
        .attr("offset", function(d) { return d.offset; })
        .attr("stop-color", function(d) { return d.color; })

已更新fiddle: https://jsfiddle.net/yw46ycse/4/

这是您正在寻找的解决方案版本吗?您可以使用透明作为停止色 {offset: "95%", color: "transparent"}.

这是你的 fiddle 的修改版本,我曾经根据你的需要制作它。

https://codepen.io/Nasir_T/pen/OjOWxz

希望对您有所帮助。