【问题标题】:How to add an if condition in my d3js example如何在我的 d3js 示例中添加 if 条件
【发布时间】:2014-03-27 09:23:50
【问题描述】:

考虑 jsfiddle 链接http://jsfiddle.net/5D5eD/5/。它有数据值 [2,2],[3,3],[4,4], [5, 4],[5.5, 5],[6, 6],[6, 7],[5,6 ]。在此示例中,最后两个值是 [6,7] 和 [5,6]。我想添加一个条件,即如果 y 值小于以前的值,那么数据点应该将 y 值增加 1 个单位。在我的情况下,从 [6,7] 到 [5,6] 的行应该被从 [6,7] 到 [5,8] 的行替换。如何在代码中实现这一点?

 var line = d3.svg.line()
 .x(function(d){return x(d[0]);})
  .y(function(d){return y(d[1]);})
 .interpolate("linear");  

   g.append("path")
  .attr("d", function(d) { return line(data)})
  .attr("transform", "translate(0,0)")
   .style("stroke-width", 2)
        .style("stroke", "steelblue")
        .style("fill", "none");
   // end of drawing lines

       main.append("g")
   .attr("class", "grid")
   .attr("transform", "translate(0," + height + ")")
   .call(make_x_axis()
   .tickSize(-height, 0, 0)
   .tickFormat(""))

    main.append("g")
   .attr("class", "grid")
   .call(make_y_axis()
   .tickSize(-width, 0, 0)
   .tickFormat(""))

    function make_x_axis() {
    return d3.svg.axis()
    .scale(x)
    .orient("bottom")
     .ticks(30)
     }

    function make_y_axis() {
    return d3.svg.axis()
    .scale(y)
    .orient("left")
    .ticks(17)
    }

【问题讨论】:

  • 图中不存在第 8 点。你想要点是 [5, 7] 吗?
  • 第 8 点不存在,它可以增加为 (Yprevious + 1)。是的,如果我能得到 [5,7] 将会很有帮助。

标签: javascript html css svg d3.js


【解决方案1】:

请看这个FIDDLE。我想这就是你想要的。

var py;
data.map(
    function(d) {
        if (d[1] < py)
            d[1] = py + 1;
        py = d[1];
    }
);

【讨论】:

  • 感谢 FernOfTheAndes,非常感谢 :)
【解决方案2】:

不知道比这更有效的方法,但它满足您的要求。

使用条件返回y在绘制圆和线中的轴值,使用:

(i&gt;0 &amp;&amp; d[1]&lt;data[i-1][1]) ? y(data[i-1][1]) : y(d[1]); (where i is index from function(d, i) { ... })

以下两行发生了变化:

// Drawing circles
g.selectAll("scatter-dots")
.data(data)
    .enter().append("svg:circle")
    .attr("cx", function (d, i) {  return x(d[0]); }) 
    .attr("cy", function (d, i) { return (i>0 && d[1]<data[i-1][1]) ? y(data[i-1][1]) : y(d[1]); }) 
    .attr("r", 5)
    .style("fill", function (d) { return color(d[0]);}) ;

// begin of drawing lines
var line = d3.svg.line()
    .x(function(d){return x(d[0]);})
.y(function(d, i){ return (i>0 && d[1]<data[i-1][1]) ? y(data[i-1][1]) : y(d[1]); })
    .interpolate("linear");  

Updated Fiddle DEMO

【讨论】:

  • ram 它只对一个值执行此操作,如果我再添加一个数据点作为 [4,5] 它会重复旧模式。
  • 将 [4, 5] 添加到 [6, 7],[5,6] 和旧模式意味着什么? [6, 7], [5, 7], [4, 7] ?
  • 在添加 [6,7],[5,6] 和 [4,5] 后我想要这个模式 jsfiddle.net/5D5eD/7
  • 我猜添加任何数据点 y 轴应该增加 1?
  • 是但仅当Y当前值
猜你喜欢
  • 2022-06-17
  • 1970-01-01
  • 2022-06-30
  • 2016-06-20
  • 2023-01-25
  • 2017-01-21
  • 1970-01-01
  • 2019-12-06
  • 1970-01-01
相关资源
最近更新 更多