Published
Edited
Sep 27, 2022
Importers
Insert cell
# D3 COLOR SCALE
Insert cell
d3= require("d3@6")
Insert cell
Insert cell
//paint= d3.scaleLinear().range(["blue","green","yellow", "red"])
paint= d3.scaleLinear()

.range(["green","yellow","red"])
Insert cell
paint(0.005)
Insert cell
{
const target= html`${
d3.ticks(0, 1, 30)
.map(paint)
.map(
t =>
`<span title="${t}"
style="background:${t};
height: 50px;
width:4%;
display: inline-block;">&nbsp;</span>`
)
}`

return target;
}
Insert cell
Insert cell
four= d3.scaleBand()
.domain(["one", "two", "three", "four"])
.range([0, 100])
Insert cell
four.bandwidth()
Insert cell
Insert cell
angryRainbow= d3.scaleSequential( t => d3.hsl( t * 360, 1, 0.5).toString())
Insert cell
angryRainbow(t0)
Insert cell
viewof t0= ramp(angryRainbow)
Insert cell
Insert cell
colorScale= d3.scaleSequential()
.domain([0, 200])
.interpolator(d3.interpolate("green","yellow", "red"));
Insert cell
viewof t1= ramp(colorScale)
Insert cell
Insert cell
viewof t3 = ramp(magnitude, d3.scaleLog(), 16)
Insert cell
// magnitude = d3.scaleSequentialLog(d3.interpolatePuBuGn).domain([1e-8, 1e8])
magnitude= d3.scaleSequentialLog(d3.interpolate("green","yellow", "red"))
Insert cell
Insert cell
// Adapted from "@mbostock/color-ramp"
function ramp(color, numscale, n = 512) {
const canvas = DOM.canvas(n, 1);
const context = canvas.getContext("2d"),
w = width + 28;
canvas.style.margin = "0 -14px";
canvas.style.width = `${w}px`;
canvas.style.height = "40px";
canvas.style.imageRendering = "pixelated";

// companion numerical scale, to define the axis.
if (numscale === undefined) numscale = d3.scaleLinear();
if (color.domain) numscale.domain(color.domain());
numscale.range([0, n]);
const t = color.ticks ? color.ticks(n) : d3.range(n).map(i => i / (n - 1));

for (let i = 0; i < t.length; ++i) {
context.fillStyle = color(t[i]);
context.fillRect((i * n) / t.length, 0, 100, 1);
}

d3.select(canvas).on("mousemove click", function(event) {
const t = numscale.invert((d3.pointer(event)[0] / w) * n);
canvas.value = t;
canvas.dispatchEvent(new CustomEvent("input"));
});
canvas.value = 0;

return canvas;
}
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more