I needed to make a categorical color scale to display in a legend for a web map. The legend symbolizes data displayed as a Leaflet tile layer, the tiles being cut from raster data. The original raster data was styled using GDAL's gdaldem
color-relief
tool with a color.txt file that defined a color ramp (see colors.txt and carbon.txt).
The idea here is to take that color.txt
file used by GDAL and generate a visual categorical color ramp from it to display in the web map (sold separately).
Built with blockbuilder.org
xxxxxxxxxx
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<svg height="200" width="500"></svg>
<script>
var svg = d3.select('svg');
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var xScaleLinear = d3.scaleLinear().range([0, width]);
var xScaleBand = d3.scaleBand().rangeRound([0, width]);
d3.text('soil_carbon.txt', function(err, data) {
data = data
.split('\n')
.map(d =>
d.split(' ').filter(d => d !== '')
)
.filter(d => d.length)
.map(d => {
return { v: d[0], r: +d[1], g: +d[2], b: +d[3] };
});
console.log(JSON.stringify(data));
// render strings for use as Sass variables (choose not to go this route)
var sassStrings = data.map(d => `$name${d.v}: rgb(${d.r}, ${d.g}, ${d.b});`);
// console.log(sassStrings);
xScaleBand.domain(data.map(d => d.v));
var g = svg.append('g');
g.selectAll('rectangle')
.data(data)
.enter().append('rect')
.attr('class', 'rectangle')
.attr('x', function(d) { return xScaleBand(d.v); })
.attr('y', 0)
.attr('width', xScaleBand.bandwidth())
.attr('height', 40)
.style('fill', function(d) { return `rgb(${d.r}, ${d.g}, ${d.b})`; });
});
</script>
</body>
https://d3js.org/d3.v4.min.js