4

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.

Chapo
  • 2,563
  • 3
  • 30
  • 60
  • `hitsPerDaybarChart.colors(function(d) {return d.hits>0 ? colorChoice("positive") : colorChoice("negative");})`? – FernOfTheAndes Feb 12 '14 at 00:28
  • I see that you are doing the same, actually...my bad. I created a simpler example mocking appending a rectangle and filling its color and it worked...so, it is definitely not in this last statement. – FernOfTheAndes Feb 12 '14 at 00:34
  • And here is the [fiddle](http://jsfiddle.net/5yxAF/), FWIW. – FernOfTheAndes Feb 12 '14 at 00:43
  • @FernOfTheAndes Thanks for trying it out but the issue seems to lie in the dc.js interpretation of the function. – Chapo Feb 12 '14 at 01:09

1 Answers1

10

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().

AJPerez
  • 3,435
  • 10
  • 61
  • 91
DJ Martin
  • 2,579
  • 20
  • 24
  • 1
    I updated your answer to mention that with the latest versions of d3, it's "scaleOrdinal" instead of "scale.ordinal". I hope that's ok :). Also, thanks, I was going crazy trying to make the colorAccessor work! – AJPerez Oct 10 '18 at 10:34