Skip to content

Instantly share code, notes, and snippets.



Last active Oct 19, 2016
What would you like to do?
d3 color scales & colorbrewer (v3)

##Explanation If viewing as a d3 block on color scales, click Open below the graphic to see full graphic. Displays the four d3 color scales plus all of Cynthia Brewer's color brewer themes. Method here is to use javascript to apply colour; note that you can use CSS instead by assigning class names to SVG elements.

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>D3 and colorbrewer color ranges in d3.js</title>
<script type="text/javascript" src=""></script>
<script src=""></script>
html, body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
text {
font-family: arial;
font-size: 12px;
} { fill: mediumblue; } { fill: crimson; } { fill: darkgreen; }
.axis path,
.axis line {
fill: none;
stroke: slategray;
shape-rendering: crispEdges;
<script type="text/javascript">
var chartWidth = 300;
var chartHeight = 50;
var f = d3.scale.category10();
var g = d3.scale.category20();
var h = d3.scale.category20b();
var ii = d3.scale.category20c();
var colorScales = [f,g,h,ii];
var colorLen = [10,20,20,20];
var svg ="body").append("svg").attr("id","svg").attr("width","100%").attr("height","300%");
var newY = 0;
var colorNames = ['Colour & category 10','Colour & category 20','Colour & category 20b','Colour & category 20c'];
for (var p=0; p<colorScales.length; p++) {
var svgGroup = svg.append("g").attr("transform","translate(0,"+(((p+1)*chartHeight)+newY)+")");
for (var q=0; q<colorLen[p]; q++) {
newY += chartHeight*colorScales.length;
var brewer = d3.entries(colorbrewer);
for (var p=0; p<brewer.length; p++) {
var svgGroup = svg.append("g").attr("transform","translate(0,"+(((p+1)*chartHeight)+newY)+")");
for (var q=0; q<brewer[p].value[d3.keys(brewer[p].value).map(Number).sort(d3.descending)[0]].length; q++) {
var svg = document.getElementById("svg");
var bb = svg.getBBox(); = bb.y + bb.height + "px";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment