有条件地设置d3符号 [英] Setting d3 symbol conditionally

查看:101
本文介绍了有条件地设置d3符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码试图根据传入的参数(0或1)确定要动态使用的符号和颜色.但是,当我尝试设置逻辑时,会出现属性d的路径错误.代码在下面

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) + ")"; });

如果我删除条件sybmol逻辑而仅将d严格地设置到一个符号或其他符号上,则一切正常,但是我无法弄清楚为什么添加条件逻辑会引起问题.这是错误:

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:

错误:属性d:预期的moveto路径命令("M"或"m"),函数n(n,r){…

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

推荐答案

使用单独的函数来创建符号并对其进行调用

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>

这篇关于有条件地设置d3符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆