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

问题描述:

我正在使用d3 v4。我想创建一个折线图,其中图形下方的区域是由从顶部的黑色到底部的光线渐变的区域填充的区域。我认为这是配置此类梯度如何让我的区域填充在我的d3折线图下方作为渐变?

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;   
} 

但你可以从我的小提琴看 - https://jsfiddle.net/yw46ycse/3/,我有什么反而是一个坚实的区域。我还需要做些什么才能让图形下方的区域成为渐变?

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

这是您的小提琴的修改版本,我用它来随你需要。

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

希望这有助于。

几个问题需要解决:

  1. 您有每到一站“水军”,所以梯度不会显示
  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; }) 

更新小提琴: https://jsfiddle.net/yw46ycse/4/

+0

谢谢您的更新。我要去的是一个渐变,从海军开始,然后渐渐消失(透明)。我会用“透明”来代替“红色”吗? – Dave

+0

https://developer.mozilla.org/zh-CN/docs/Web/SVG/Attribute/stop-opacity –

+0

我试图用你的小提琴中的“stop-opactiy”替换“stop-color”,但是这让我留下了完全黑色而没有任何倾斜的区域。如果我是一个CSS家伙,我可能会更好地知道如何处理它。 – Dave