Skip to content

Instantly share code, notes, and snippets.

@nick3499
Forked from d3byex/index.html
Last active March 3, 2017 18:20
Show Gist options
  • Save nick3499/e1e10730373677098cd439c5cfb2bc91 to your computer and use it in GitHub Desktop.
Save nick3499/e1e10730373677098cd439c5cfb2bc91 to your computer and use it in GitHub Desktop.
D3byEX 5.7: Categorical / Ordinal Colors (Adapted to D3.js v4)
<!DOCTYPE html>
<html>
<meta charset=utf-8>
<head>
<meta name="description"
content="D3.js v4, d3.scaleOrdinal(d3.schemeCategory10)
categorical ordinal colors" />
</head>
<body>
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-selection-multi.v1.min.js"></script>
<script>
var data = d3.range(0, 9);
// ordinal scale; categorical color scheme
var colorScale = d3.scaleOrdinal(d3.schemeCategory10); // v4
var svg = d3.select('body')
.append('svg')
.attrs({width: 200, height: 20}); // selection multi
svg.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attrs({fill: function(d) { return colorScale(d); },
x: function(d, i) { return i * 20 },
width: 20, height: 20});
</script>
</body>
</html>
@nick3499
Copy link
Author

nick3499 commented Mar 2, 2017

View demo at Codepen: Categorical Ordinal Scale Colors

d3js.org/d3-selection-multi.v1.min.js library facilitates .attrs() convenience function.
d3.scaleOrdinal(d3.schemeCategory10) is a v4 function which combines ordinal scaling with a categorical color scheme.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment