Last active
February 25, 2020 14:21
-
-
Save pstuffa/3393ff2711a53975040077b7453781a9 to your computer and use it in GitHub Desktop.
4.0 Color Scales - Ordinal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment