Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>D3 Color Scales</h1>

<div class="wrapper">
	<div class="scale-wrapper">
		<h2>Linear scale</h2>
		<div data-scale="linear"></div>
	</div>

	<div class="scale-wrapper">
		<h2>Diverging scale</h2>
		<div data-scale="diverging"></div>
	</div>

	<div class="scale-wrapper">
		<h2>Threshold scale</h2>
		<div data-scale="threshold"></div>
	</div>
</div>
              
            
!

CSS

              
                * {
	box-sizing: border-box;
}

body {
	font-family: "Open Sans", sans-serif;
	padding: clamp(1rem, 8vw, 5rem);
	background: whitesmoke;
}

.wrapper,
h1 {
	margin-inline: auto;
	max-width: 800px;
}

.scale-wrapper {
	margin-bottom: 10rem;
}

[data-scale] {
	aspect-ratio: 6 / 1;
	position: relative;
}

p {
	margin: 0;
}

.marker {
	position: absolute;
	min-width: 9rem;
	top: calc(100% + 0.5rem);
	background: white;
	padding: 0.5rem 1rem;
	border-radius: 0.5rem;
	box-shadow: 0.1rem 0.1rem 0.5rem rgb(0 0 0 / 0.1);
	transform: translate3d(-50%, 0, 0);
	text-align: center;
	display: flex;
	flex-direction: column;
	align-items: center;
	gap: 0.5rem;
	cursor: grab;
	z-index: 1;
}

.marker::after {
	content: '';
	position: absolute;
	bottom: 100%;
	left: 50%;
	width: 1rem;
	height: 1.5rem;
	background: white;
	transform: translate3d(-50%, 0, 0);
	clip-path: polygon(50% 50%, 100% 100%, 0 100%);
}

.marker__color {
	width: 2rem;
	height: 2rem;
	border-radius: 50%;
}

.marker code {
	font-size: 0.7rem;
}

.marker * {
	pointer-events: none;
}
              
            
!

JS

              
                const linearScaleEl = document.querySelector('[data-scale="linear"]')
const divergingScaleEl = document.querySelector('[data-scale="diverging"]')
const thresholdScaleEl = document.querySelector('[data-scale="threshold"]')


const defaults = {
	colorRange: ['royalblue', 'pink'],
	positions: [0, 50, 100],
	scaleType: 'linear',
}

class ColorScale {
	constructor(el, opts) {
		this.el = d3.select(el)
		this.options = { ...defaults, ...opts }
		this.positions = this.options.positions
		this.colorRange = this.options.colorRange
		this.isDragging = false
		this.scaleType = this.el.node().dataset.scale
		
		this.setBgGradient()
		this.addMarkers()
	}
	
	get domainThreshold() {
		const step = 100 / this.colorRange.length
		return this.colorRange.map((color, i) => {
			return (i + 1) * step
		})
	}
	
	get domainLinear() {
		if (this.colorRange.length === 2) {
			return [0, 100]
		}
		
		const step = 100 / this.colorRange.length
		return this.colorRange.map((color, i) => {
			return i * step
		})
	}
	
	get colorScaleLinear() {
		return d3.scaleLinear()
			.domain(this.domainLinear)
			.range(this.colorRange)
			.clamp(true)
	}
	
	get colorScaleDiverging() {
		const domain = [0, 50, 100]
		
		return d3.scaleDiverging()
			.domain(domain)
			.range(this.colorRange)
			.clamp(true)
	}
	
	get colorScaleThreshold() {
		return d3.scaleThreshold()
			.domain(this.domainThreshold)
			.range(this.colorRange)
	}
	
	get colorScaleFn() {
		if (this.scaleType === 'diverging') {
			return this.colorScaleDiverging
		}
		
		if (this.scaleType === 'threshold') {
			return this.colorScaleThreshold
		}
		
		return this.colorScaleLinear
	}
	
	get scalePosition() {
		return d3.scaleLinear()
			.domain([0, this.el.node().clientWidth])
			.range([0, 100])
			.clamp(true)
	}
	
	setBgGradient() {
		let stops = this.colorRange.join(',')
		
		if (this.scaleType === 'threshold') {
			const step = 100 / this.colorRange.length
			stops = this.colorRange.map((color, i) => {
				const stop = ((i + 1) * step)
				return `${color} 0, ${color} ${stop}%`
			}).join(',')
		}
		
		this.el.style('background', `linear-gradient(
			to right, ${stops})`)
	}
	
	createMarker(position) {
		const marker = this.el.append('div')
			.attr('class', 'marker')
			.style('left', `${position}%`)
		
		const positionText = marker.append('p')
			.text(`${position}%`)
		
		const colorSpot = marker.append('div')
			.attr('class', 'marker__color')
			.style('background-color', `${this.colorScaleFn(position)}`)
		
		const scaleText = marker.append('code')
			.html(`colorScale(${position})<br/>${this.colorScaleFn(position)}`)
		
		marker.on('mousedown touchstart', () => {
			this.isDragging = true
			marker.style('z-index', 2)
		}).on('mouseup touchend', () => {
			this.isDragging = false
			marker.style('z-index', 1)
		}).on('mousemove touchmove', (e) => {
			if (!this.isDragging) return
			
			const [posX, posY] = d3.pointer(e, this.el)
			const elPosX = this.el.node().getBoundingClientRect().left
			const percentage = this.scalePosition(posX - elPosX).toFixed(0)
			const color = this.colorScaleFn(percentage)
			
			marker.style('left', `${percentage}%`)
			positionText.text(`${percentage}%`)
			colorSpot.style('background-color', `${color}`)
			scaleText.html(`scale(${percentage})<br/>${color}`)
		})
	}
	
	addMarkers() {
		this.positions.forEach((position) => this.createMarker(position))
	}
	
	colorSwatch(el) {
		d3.select(el).style('background-color', this.colorScaleFn(200))
	}
}

const simpleLinearPalette = ['royalblue', 'pink']
const fiveColorPalette = ['royalblue', 'lightblue', 'aliceblue', 'lavender', 'pink']

const linearScaleVisualiser = new ColorScale(linearScaleEl, {
	colorRange: simpleLinearPalette
})

const divergingScaleVisualiser = new ColorScale(divergingScaleEl, {
	colorRange: ['royalblue', 'lightblue', 'mediumpurple']
})

const thresholdScaleVisualiser = new ColorScale(thresholdScaleEl, {
	colorRange: ['royalblue', 'lightblue', 'aliceblue', 'lavender', 'mediumpurple']
})
              
            
!
999px

Console