简体   繁体   中英

How to modify D3js graph depending on change of value?

I have a graph which I build using d3js and I want to draw red line or other kind of indicator on the graph to indicate when the graphs blue line's value hits 0(in this case its 6th of june). The example of a graph http://jsfiddle.net/wRDXt/81/

My starting point is:

if(dataset.value = 0){
   //draw line 
}

But I have no clue where to go from here. Any help would be greatly appreciated.

There are a few different ways to do this. One way would be to filter the dataset to create a new array that only had the entries with a value of 0.

var zeroData = dataset.filter(function(d){
    if (d.value == 0) return d; 
});

This new array could be used to draw lines at each zero point with a separate svg.selectAll(".redlines") using the new array as the data.

// plot lines
svg.selectAll(".redline")
    .data(zeroData)
    .enter()
    .append("line")
    .attr("class", "redline")
    .attr("x1", function(d) { return xScale(d.date); })
    .attr("x2", function(d) { return xScale(d.date); })
    .attr("y1", 0)
    .attr("y2", 250)
    .style("stroke", "#ff0000");

http://jsfiddle.net/wRDXt/85/

Another way is to start by appending a "g" element for each data point instead of a circle then adding a circle and a line for each point. Styling can be used to make only the value == 0 points visible.

// plot data points as g elements
var datapts = svg.selectAll(".data-point")
    .data(dataset);

var dataptsEnter = datapts
    .enter()
    .append("g")
    .attr("class", "data-point")
    .attr("transform", function(d) {
        return "translate(" + xScale(d.date) + "," + yScale(d.value) + ")";

    });

dataptsEnter
    .append("circle")
    .attr("class", "data-point-circle")
    .attr("cx", 0)
    .attr("cy", 0)
    .attr("r", 5);

dataptsEnter
    .append("line")
    .attr("x1", 0)
    .attr("y1", 0)
    .attr("x2", 0)
    .attr("y2", -50)
    .style("stroke", "#ff0000")
    .style("opacity", function(d) {
        if (d.value == 0) return 1;
        return 0;
    });

http://jsfiddle.net/wRDXt/82/

In the second approach, there is a red line for each datapoint but opacity is used to make only the zero value visible.

The first approach is the one I'd use.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM