Changing bar colours based on value

Hi, newbie here.

I’m drawing a chart from some JSON and want to colour the bars depending on a field in the data: green on ‘success’ and red on ‘failed’. This sounds like it should be trivial but for some reason I’m stuggling to make it actually work… Anyone got an example of mapping a set of values to specific colours?

Cheers,
Ross

The d3 scale is what you need.

getColour = d3.scaleOrdinal()
  .domain([‘success’ ,‘failed’])
  .range(["green", "red"])

Calling it would look like this if filling a SVG rect

.attr('fill', d => getColour(d.result))

d.result is the json name for the success or fail

So I was on the right track with the scaleOrdinal at least. I’m using Plot.barX(), but fill: d => colourmap(d.status) appears to be using the ‘green’ and ‘red’ as opaque strings and keying them into the standard colour map.

Aha so when using Plot you don’t create anything by hand.

A new scale, for example:

  color: {
    type: "categorical",
    domain: ["success", "failed"],
    range: ["green", "red"]
  }

And then you can use it in the barX() method like fill: "status".

It’s possible to create colors by hand, if you specify:

  color: {  type: "identity" }

(however it’s not the recommended approach).