Tim Lindsey
Tim Lindsey

Reputation: 757

Setting d3 symbol conditionally

I have a piece of code where I'm trying to determine the symbol and color to use dynamically based on a parameter being passed in (0 or 1). However I get a path error for attribute d when I try and set up the logic. Code is below

  svg.selectAll(".point")
      .data(data)
    .enter()
      .append("path")
      .attr("class", "point")
      .attr("d", function(d){
        if(d.zeroOrOne == 1){
          return d3.svg.symbol().type("cross");
        }else if (d.zeroOrOne == 0){
          return d3.svg.symbol().type("circle");
        }
      })<
      .attr('fill', 'none')
      .attr('stroke', function(d){
        if(d.zeroOrOne == 1){
          return 'blue';
        }else if (d.zeroOrOne == 0){
          return 'red';
        }
      })
      .attr("transform", function(d) { return "translate(" + ratingScale(d.xParam) + "," + winsNomsScale(d.yParam) + ")"; });

If I remove the conditional sybmol logic and just d strictly to one symbol or the other everything works, but I can't figure out why adding the conditional logic is causing problems. Here's the error:

Error: attribute d: Expected moveto path command ('M' or 'm'), "function n(n,r){…

Upvotes: 2

Views: 1665

Answers (1)

Umesh Maharshi
Umesh Maharshi

Reputation: 1591

Use a separate function for creating symbols and call it

var data = [{"zeroOrOne" : 0 }, {"zeroOrOne" : 1 }, {"zeroOrOne" : 2 }];

// use this for generating symbols
var arc = d3.svg.symbol().type(function(d) { 
	if(d.zeroOrOne == 0) {
		return "circle";
	}
	else if(d.zeroOrOne == 1) {
		return "cross";
	}
	else return "triangle-up";
});

 d3.select("#graph").selectAll(".point")
      .data(data)
    .enter()
      .append("path")
      .attr("class", "point")
      .attr("d", arc)
      .attr('fill', 'none')
      .attr('stroke', function(d){
        if(d.zeroOrOne == 1){
          return 'blue';
        }else if (d.zeroOrOne == 0){
          return 'red';
        }
		else return "green";
      })
      .attr("transform", function(d, i) { return "translate(" + (i + 1) * 20 + " ,30 )"; });
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<svg id="graph" width="200", height="200" >
</svg>

Upvotes: 2

Related Questions