How to use a colorbrewer scale
d3.js, javascript
Solution
One possibility is changing `http` to `https` in your reference, or changing the reference itself (I'm getting a "connection timed out" with your src):
<script src="https://d3js.org/colorbrewer.v1.min.js"></script>
Other than that, a Brewer scale is just an array, and it's used as you use an array in any other D3 scale.
Here is a working demo. First, we set the scale:
var colorScale = d3.scale.quantize()
.range(colorbrewer.YlGnBu[9])
.domain([0,9]);
Which is equivalent to:
var colorScale = d3.scale.quantize()
.range(["#ffffd9","#edf8b1","#c7e9b4","#7fcdbb",
"#41b6c4","#1d91c0","#225ea8","#253494","#081d58"])
.domain([0,9]);
And then we use it to color the circles:
.attr("fill", function(d){ return colorScale(d)});
Check the demo:
var dataset = d3.range(9);
var colorScale = d3.scale.quantize()
.range(colorbrewer.YlGnBu[9])
.domain([0, 9]);
var svg = d3.select("body")
.append("svg");
var circles = svg.selectAll(".circles")
.data(dataset)
.enter()
.append("circle");
circles.attr("cy", 50)
.attr("cx", function(d) {
return 50 + d * 20
})
.attr("r", 10)
.attr("fill", function(d) {
return colorScale(d)
});
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://d3js.org/colorbrewer.v1.min.js"></script>
EDIT: Your bars in the plunkr are black for a reason. You're defining the `colorScale` as a quantize:
var colorScale = d3.scale.quantize()
.range(colorbrewer.YlGnBu[9])
.domain([0, 8]);
But then, later, you're setting it a qualitative domain!
colorScale.domain(layers.map(function(layer) {
return layer.key;
}));
This will simply not work! According to the API (emphases mine):
Quantize scales are a variant of linear scales with a discrete rather than continuous range. The input domain is still continuous, and divided into uniform segments based on the number of values in (the cardinality of) the output range.
Thus, you'll have to decide what you want. This is a plunkr with the ordinal scale: https://plnkr.co/edit/qYi0y4A49UIDawZBr5kF?p=preview
Problem
I have the following: ``` <script src="http://colorbrewer2.org/export/colorbrewer.js"></script> ... ... var colorScale = d3.scale.quantize() .range(colorbrewer.YlGnBu[9]); ... ... colorScale.domain([0,layers.length]); console.log(layers.length) //<<< this returns 8 ``` The whole chart is coming through as black - why are the colorbrewer colors not being used? update Here is a full working (black!) example: https://plnkr.co/edit/JqL0rYIjhZz9gf6102j7?p=preview