.colors function in barChart dc.js with only two options

╄→гoц情女王★ 提交于 2019-12-05 02:04:58

问题


I want to create a color function which shows red when the value is negative and green otherwise in a barChart.

Here is what I've come up with so far :

var colorChoice = d3.scale.ordinal().domain(["positive","negative"])
                                    .range(["#00FF00","#FF0000"]);
hitsPerDaybarChart
.colors(function(d) {return(colorChoice((d.hits>0) ? "positive":"negative"));})

But I get the following error message : TypeError: Object function (d) {return(colorChoice((d.pnl>0) ? "positive":"negative"));} has no method 'range'.

All help welcome. Thanks.


回答1:


You will want to use the colorAccessor function.

1) Define your color range and domain:

.colors(d3.scale.ordinal().domain(["positive", "negative"])
                          .range(["#00FF00", "#FF0000"]))

2) Define your color accessor:

.colorAccessor(function(d) {
  if (d.value > 0) {
    return "positive";
  }
  return "negative";
})

Hopefully this JSFiddle helps: http://jsfiddle.net/djmartin_umich/9ELWV/


Note: with the latest versions of d3.js, use d3.scaleOrdinal() instead of d3.scale.ordinal().



来源:https://stackoverflow.com/questions/21715990/colors-function-in-barchart-dc-js-with-only-two-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!