D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
pstuffa
Full window
Github gist
4.0 Color Scales - Ordinal
<!DOCTYPE html> <html> <body> <style> body { font: 12px sans-serif; } div { max-width: 950px; } </style> <div class="container"></div> <div class="categoricalButtons">Ordinal Color Scales: </div> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="//d3js.org/d3-scale-chromatic.v0.3.min.js"></script> <script> var categorical = [ { "name" : "schemeAccent", "n": 8}, { "name" : "schemeDark2", "n": 8}, { "name" : "schemePastel2", "n": 8}, { "name" : "schemeSet2", "n": 8}, { "name" : "schemeSet1", "n": 9}, { "name" : "schemePastel1", "n": 9}, { "name" : "schemeCategory10", "n" : 10}, { "name" : "schemeSet3", "n" : 12 }, { "name" : "schemePaired", "n": 12}, { "name" : "schemeCategory20", "n" : 20 }, { "name" : "schemeCategory20b", "n" : 20}, { "name" : "schemeCategory20c", "n" : 20 } ] var width = 960, height = 500; var svg = d3.select("body") .append("svg") .attr("width", width) .attr("height", height) .append("g") var colorScale = d3.scaleOrdinal(d3[categorical[0].name]) var n = categorical[0].n, unit = width/n; var bars = svg.selectAll(".bars") .data(d3.range(n), function(d) { return d; }) .enter().append("rect") .attr("class", "bars") .attr("x", function(d, i) { return i * unit; }) .attr("y", 0) .attr("height", height) .attr("width", unit) .style("fill", function(d, i ) { return colorScale(d); }) var sequentialButtons = d3.select(".categoricalButtons") .selectAll("button") .data(categorical) .enter().append("button") .text(function(d) { return d.name; }) .on("click", function(buttonValue) { var colorScale = d3.scaleOrdinal(d3[buttonValue.name]); var bars = svg.selectAll(".bars") .data(d3.range(buttonValue.n), function(d) { return d; }); bars.exit() .remove(); bars.transition() .attr("x", function(d, i) { return i*(width/buttonValue.n); }) .attr("width", width/buttonValue.n) .style("fill", function(d, i) { return colorScale(i); }); bars.enter().append("rect") .attr("class", "bars") .attr("y", 0) .attr("height", height) .attr("x", function(d, i) { return i*(width/buttonValue.n); }) .attr("width", width/buttonValue.n) .style("fill", function(d, i) { return colorScale(i); }); }); </script>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v0.3.min.js