legend = () => {
const k = 24;
const arrow = DOM.uid();
const nanRectY = n * k + 30;
return svg`<g font-family=sans-serif font-size=10>
<g transform="translate(-${k * n / 2},-${k * n / 2})
rotate(-45 ${k * n / 2},${k * n / 2})">
//Positions the group by translating it to the center at the midpoint, calculated using n and k, and rotates the group -45 degrees around the center
<marker id="${arrow.id}" markerHeight=10 markerWidth=10 refX=6 refY=3 orient=auto>
<path d="M0,0L9,3L0,6Z" />
</marker>
//Creates a marker element (arrow) used to create arrowheads for the legend and sets width and height. Sets refrence point for marker to position on lines. Defines shape of arrowhead.
${d3.cross(d3.range(n), d3.range(n)).map(([i, j]) => svg`<rect width=${k} height=${k} x=${i * k} y=${(n - 1 - j) * k} fill=${colors[j * n + i]}>
<title>${data.title[0]}${labels[j] && ` (${labels[j]})`}
${data.title[1]}${labels[i] && ` (${labels[i]})`}</title>
</rect>`)}
//Creates pairwise combinations of both variables, creating a grid. Iterates through the grid and creates a rectangle for each pair, sets the dimensions, position, and assigns a color. Also adds tooltip which displays info for each rectangle
<line marker-end="${arrow}" x1=0 x2=${n * k} y1=${n * k} y2=${n * k} stroke=black stroke-width=1.5 />
<line marker-end="${arrow}" y2=0 y1=${n * k} stroke=black stroke-width=1.5 />
//Adds two drawn arrow lines horizontal and vertical, and sets color and width
<text font-weight="bold" dy="1.5em" transform="rotate(90) translate(${n / 2 * k},6)" text-anchor="middle">${data.title[0]}</text>
<text font-weight="bold" dy="1.5em" transform="translate(${n / 2 * k},${n * k + 6})" text-anchor="middle">${data.title[1]}</text>
//adds text for labels of axes
<rect width=${k} height=${k} x=0 y=${nanRectY} fill="black">
<title>NaN</title>
</rect>
<text x=${k + 5} y=${nanRectY + k / 2} font-weight="bold" dy="0.35em" font-size="10">No Data</text>
</g>
</g>`;
}