如何在路径属性处手动应用 d3js 中的颜色过渡



虽然在源下方绘制地平线图没有给出预期的结果;0=1:红色,d<0:绿色;但是它仅通过应用黑色运行,请启发以纠正此问题。

data=[0.2,1.3,1.1,1.3.0.9]
        var color =
            d3.scale.threshold()
                .domain([0,1])
                  .range(["green", "yellow", "red"]);       
        path.enter().append("path")
                    .style("fill", function (d,i) { return color(i);})
                    .attr("transform", t0)
                    .attr("d", d0);
d3.transition(path)
.style("fill", function(d,i) { return color(i); })
    .attr("transform", t1)
    .attr("d", d1);

您应该将过渡应用于fill属性。

  lineGraph
    .data([newValue])
    .transition()
    .duration(1500)
    .attr('fill', function(d) { return color(d); })

根据您的代码查看下面的演示:

var svg = d3.select("svg")
var dataset = [
  [10, 25],
  [10, 75],
   [40, 75],
]
var color =
  d3.scale.threshold()
  .domain([0, 1])
  .range(["green", "yellow", "red"]);
var lineFunction = d3.svg.line()
  .x(function(d) {
    return d[0];
  })
  .y(function(d) {
    return d[1];
  })
  .interpolate("linear");
  
var lineGraph = svg.append("path")
  .attr("d", lineFunction(dataset))
  .attr("fill", "red")
var colorValues = [-1, 0.5, 2];
var colorIndex = 0;
setInterval(function() {
  colorIndex++;
	var newValue = colorValues[(colorIndex + colorValues.length)  % colorValues.length];
  d3.select('#color-value').text(newValue)
  lineGraph
  	.data([newValue])
    .transition()
    .duration(1500)
    .attr('fill', function(d) { return color(d); })
}, 3000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>
value: <div id="color-value"></div>
<svg width="500" height="80">
</svg>

最新更新