block by jonsadka 5054e6a53e25a7582d4d73d3958fbbf9

Nonlinear Color Scales

Full Screen

Built with blockbuilder.org

See https://github.com/d3/d3-scale/issues/62 for updates on this workaround

index.html

<!DOCTYPE html>
<head>
  <meta charset="utf-8">
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
  <style>
    body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
    text {font: Verdana, arial;}
  </style>
</head>

<body>
  <script>
    const width = 960;
    const height = 500;
    const margin = 40;
    const barHeight = 50;
    const barWidth = 20;
    const numBars = (width - 2 * margin) / barWidth;

    const start = 1;
    const end = (width - 2 * margin);
    const points = d3.range(start, end, barWidth)
    
    // Linear Scale
    const colorScaleLinear = d3.scaleSequential(
        d3.interpolateReds
      )
      .domain([start, end])

    // Exponential Scale
    const expScale = d3.scalePow()
      .exponent(Math.E)
      .domain([start, end])
    const colorScaleExp = d3.scaleSequential(
        (d) => d3.interpolateReds(expScale(d))
      )

    // Log Scale
    const logScale = d3.scaleLog()
      .domain([start, end])
    const colorScaleLog = d3.scaleSequential(
        (d) => d3.interpolateReds(logScale(d))
      )   
    
    const svg = d3.select('body').append('svg')
      .attr('width', width)
      .attr('height', 500)

    const scales = [colorScaleLinear, colorScaleExp, colorScaleLog];
    scales.forEach((scale, i) => {
      svg.append('g')
          .attr('class', 'scale-' + i)
          .attr('transform', 'translate(' + margin + ',' +  (2 * margin + i * 3 * barHeight) + ')')
        .selectAll('bars').data(points).enter()
        .append('rect')
          .attr('y', 0)
          .attr('x', (d, i) => i * barWidth)
          .attr('width', barWidth)
          .attr('height', barHeight)
          .attr('fill', scale)
      
      d3.select('.scale-' + i).append('text')
        .text(i === 0 ? 'Linear' : i === 1 ? 'Exponential' : 'Logarithmic')
        .attr('x', 0)
        .attr('y', -10)
        .attr('fill', '#333')

    })
  </script>
</body>