D3
OG
Old school D3 from simpler times
All examples
By author
By category
About
RobinL
Full window
Github gist
logarithmic colour scale
Built with
blockbuilder.org
<!DOCTYPE html> <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> <script> // Feel free to change or delete any of the code you see in this editor! var svg = d3.select("body").append("svg") .attr("width", 960) .attr("height", 500) var domain = [0.5,10] var range = [0,500] var colour_range = ["#6AE817","#FFA200", "#B30409"] g = svg.append("g") .attr("transform","translate(100,100)") var logScale = d3.scaleLog().domain(domain).range(range) var linearScale = d3.scaleLinear().domain(domain).range(range) //Map colours across the range in equal intervals var num_colours = colour_range.length var diff = range[1] - range[0] var step = diff / (colour_range.length - 1) var for_inversion = d3.range(num_colours).map(function(d) {return range[0] + d*step}) var log_colour_values = for_inversion.map(logScale.invert) var logColour_scale = d3.scaleLog().domain(log_colour_values).range(colour_range) debugger; //Now plot rectangles var num_rectangles = 100 var step = diff/num_rectangles var rect_data = d3.range(num_rectangles).map(function(d) {return range[0] + d*step}) g.selectAll("rect").data(rect_data).enter() .append("rect") .attr("x", function(d) {return d}) .attr("y", function(d) {return 100}) .attr("height", function(d) {return 20}) .attr("width", function(d) {return diff/num_rectangles}) .attr("fill", function(d) { return logColour_scale(logScale.invert(d)) }) g .append("rect") .attr("x", function(d) {return d}) .attr("y", function(d) {return 200}) .attr("height", function(d) {return 20}) .attr("width", function(d) {return diff/num_rectangles}) .attr("fill", function(d) { return logColour_scale(0.5) }) //What number in the domain is half way along the logscale? var axis = d3.axisBottom(logScale).tickFormat(d3.format(",.1f")) g.call(axis) </script> </body>
https://d3js.org/d3.v4.min.js