在D3中使用三元 [英] Using ternary in D3

查看:80
本文介绍了在D3中使用三元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试弄清楚如何在D3中使用三元运算符使用多个条件(仍然可以在D3中找到方法).我有一个带有立法列的电子表格,包含的值是Yes1,Yes2,Yes3和No.对于Yes1,我想将我的圆圈涂成红色,Yes2是粉红色,Yes3是橙色,而No是灰色.下面的代码将所有圆圈涂成红色或粉红色.

I'm trying to work out how I can use multiple conditions with ternary operator in D3 (still finding my way with D3). I have a spreadsheet with a column legislative and the values included are Yes1, Yes2, Yes3 and No. For Yes1 I want to color my circles red, Yes2 are pink, Yes3 are orange and No are grey. The code below colors all circles either red or pink only.

.style("fill", function(d) { 
    return (d.data.legislative == "Yes1" ? "red" : "grey" || "Yes2" ? "pink" : "grey" || "Yes3" ? "orange" : "grey");
})

推荐答案

在D3中,习惯上将标度用于两组值之间的这种类型的映射.

In D3 it is convention to use a scale for this type of mapping between two sets of values.

在您的情况下,您将创建一个有序刻度,例如:

In your case, you would create an ordinal scale, such as:

let colour = d3.scaleOrdinal()
.domain(["Yes1", "Yes2", "Yes3", "No"])
.range(["red", "pink", "orange", "grey"])

然后在样式函数中,您将使用色标基于d.data.legislative的值返回颜色:

and then in your style function you would use the colour scale to return the colour based on the value of d.data.legislative:

.style("fill", function(d) { return colour(d.data.legislative) })

这篇关于在D3中使用三元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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