p5/D3 Cookbook

Combining the power of D3.js with the simplicity of p5.js

Using D3 Scales in p5

D3 Concepts Used

d3.scale.linear()

D3 scales can be used directly in p5 sketches. D3 scales offer a range of interpolation options. These include interpolating colors and multi-step scales.

Like most D3 functions, we must set D3 scale's settings though initial function creation using D3.scale.linear(). D3.scale.linear() will return a new function that we can use to translate numbers and strings into different scales

var d3xScale = d3.scale.linear()
  .domain([0,1])
  .range([0,50]);

Now with d3xScale, we can pass values to it to be rescaled:

var x = d3xScale(.5) // returns 25

In addition to numbers, D3.scale also can output a range of colors instead of numbers:

var colorScale = d3.scale.linear()
  .domain([0,1])
  .range(['#aaa','#ddd']);

D3.scale also allows intermediate points to be defined.

var colorScale = d3.scale.linear()
  .domain([0,.5,1])
  .range(['#aaa','#ee33ee,'#ddd']);

The Complete Code

function setup() {
      
      //Create the p5 canvas
      var width = 500,
          height = 300,
          margin = 30;
      
      var c = createCanvas(width + margin*2, height + margin*2);
      c.parent('example-recipe');
      stroke("#fff");
      
      //Set the output range of the different scales.
      var radius = 10,
          maxRadius = 70
          startColor = "#033E8C",
          midColor = "#00D96F";
          endColor = "#F2B705";
      
      
      /*
      Create the three different scales used in this example. Each scale returns a function. So the variable d3xScale can be used as if it were a function such as d3xScale(.5)
      */
      var d3xScale = d3.scale.linear()
        .domain([0,1])
        .range([margin,margin+width]);
      
      var d3colorScale = d3.scale.linear()
        .domain([0,.5,1])
        .range([startColor,midColor,endColor]);
      
      var d3radiusScale = d3.scale.linear()
        .domain([0,1])
        .range([radius,maxRadius]);

      /*
      Create a for loop and draw an ellipse using p5's drawing syntax.
      */
      for(var i = 0; i < 1; i += .01) {
        var scaledX = d3xScale(i);
        var scaledColor = d3colorScale(i);
        var scaledRadius = d3radiusScale(i);
        fill(scaledColor);
        ellipse(scaledX, maxRadius, scaledRadius, scaledRadius);
      }
      
      //Add a title
      fill('#000');
      noStroke();
      textSize(15);
      text("Using D3.js scales in a p5 sketch", 30, 30);
    }