Symbol generator

The symbol generator returns path data for a number of predefined symbol types (circle, square, triangle, star etc.) that can be associated with categories as in a scatterplot. Symbols are centered at the origin. You can use a transform to move the symbol to a desired position.

The next example appends two circles (type d3.symbolCircle) in two different ways. The size of the symbol refers to its area.

const svg ="svg")
  .attr("width", "100%")
  .attr("height", "100%")
  .attr("viewBox", `0 0 100 30`)

  .style('fill', "red")
  .attr("transform", "translate(10,15)")
  .attr("d", d3.symbol(d3.symbolCircle, 78.5))

  .style('fill', "green")
  .attr("transform", "translate(20,15)")
  .attr("d", d3.symbol()
    .size(78.5) // radius = approx. 5


Fill or stroke

Some symbols are designed for filling, other symbols are designed for stroking and only symbolCircle is designed for both filling and striking.

d3.symbolsFill returns an array containing a set of symbol types designed for filling. d3.symbolsStroke returns an array containing a set of symbol types designed for stroking. Both are useful for a categorical shape encoding with an ordinal scale.

const shapeScale = d3.scaleOrdinal(["a", "b", "c"], d3.symbolsFill);

    .attr("transform", "translate(20, 20)")
    .attr("d", d3.symbol(shapeScale("c")));

Next example shows all symbols:



// Code for the symbolsFill figure above:

const margin = {top: 10, right: 40, bottom: 30, left: 40},
      width = 640,
      height = 60;		

const svg ="svg")
  .attr("width", "100%")
  .attr("height", "100%")
  .attr("viewBox", `0 0 ${width} ${height}`);		  

const symbolNames = [ "symbolCircle", "symbolCross", "symbolDiamond", "symbolSquare", "symbolStar", "symbolTriangle", "symbolWye" ];
const scaleX = d3.scalePoint()
  .range([margin.left, width - margin.right]);
const shapeScale = d3.scaleOrdinal(symbolNames, d3.symbolsFill);  

// Add X axis:
  .attr("transform", `translate(0,${height - margin.bottom})`)
  .call(g =>".domain").remove());

// Add symbols:  
    .attr("transform", (d, i) => `translate(${scaleX(d)}, ${height - margin.bottom - 15})`)
    .attr("d", d => d3.symbol(shapeScale(d))())		
    .attr("stroke", "none")
    .attr("fill", "currentColor");