d3.js:如何有条件地渲染曲线?

时间:2014-07-02 12:41:08

标签: javascript d3.js

我有一个函数可以通过我给出的点作为参数绘制曲线,如下所示:

var data = [
  // stage 1-9, intensity %, draw disk
  {x:1, y:  0, point:true},
  {x:4, y: 30, point:true},
  {x:5, y: 70, point:true},
  {x:6, y:100, point:true},
  {x:7, y: 90, point:true},
  {x:8, y: 40, point:true},
  {x:9, y: 10, point:false}
];

我想处理点成员,告诉他们是否要画一个额外的位置。

怎么做?

按今天绘制曲线的函数:

function curveChart(data) {

    for (i in data) {
        data[i].y = 5.5*data[i].y/100;  // normalize
        data[i].id = i;
    }

    var margin  = {top: 10, right: 190, bottom: 275, left: 35},
        width   = 915 - margin.left - margin.right,
        height  = 500 - margin.top - margin.bottom;

    var x = d3.scale.linear() //.time.scale()
        .domain([1, 9])     // 9 stages
        .range([0, width]);

    var y = d3.scale.linear()
        .domain([0, 6])
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom");

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");

    var line = d3.svg.line()
        .interpolate("monotone")
        .x(function(d) { return x(d.x); })
        .y(function(d) { return y(d.y); });

    var svg = d3.select(".curveChart").append("svg")
        .datum(data)
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
      .append("g")
        .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    svg.append("path")
        .attr("class", "line")
        .attr("d", line);

    var n = 1;
                svg.selectAll("circle")
                    .data(data)
                    .enter()
                    .append("circle")
                    .attr("class", "dot")
                    .attr("cx", line.x())
                    .attr("cy", line.y())
                    .attr("r", 2)
                    .attr("bubbleid", function(d){return d.id; })
                    .transition(1000)
                    .duration(800)
                    .attr("r", 10);

    svg.selectAll("circle").on("click", function(){

        d3.selectAll(".active").classed("active", false);
        d3.select(this).classed("active", true);

        var id = $(this).attr('bubbleid');
        console.log("clicked on "+$(this).attr('bubbleid'));

        $(".bubble").removeClass("show");
        $("#bubble"+id).addClass("show");

        d3.select(this)
        .transition()
        .duration(400)
            .attr('r', 25)
            .transition()
            .duration(400)
                .attr('r', 10)
                ;
    });
}

小提琴:http://jsfiddle.net/stephanedeluca/R44cB/

1 个答案:

答案 0 :(得分:0)

最简单的方法是在将数据传递给.data()之前过滤数据,只保留point为真的元素:

svg.selectAll("circle")
            .data(data.filter(function(d) { return d.point; }))

完整演示here

相关问题