Day 6: Size & Range

In the force layout, we don’t have an axis. However, in normal charts, we will have axes. To map our data to the x-axis and y-axis, we will need to figure out the canvas size and range of the d3 scale functions.

First, we need to set the width and height of the SVG element. Then, we need to have an area to draw our charts. Below are the codes to set up the dimensions. svgWidth is based on the screen size, so the chart will be larger if the screen size is bigger. Also, the margin on the left and bottom are larger because we usually put axes there.

const margin = { left: 100, right: 10, top: 10, bottom: 100 }
const svgWidth = window.innerWidth * 0.9
// or use a fixed width 
// const svgWidth = 900
const svgHeight = svgWidth * 0.6
const chartWidth = svgWidth - margin.left - margin.right
const chartHeight = svgHeight - margin.top - margin.bottom

The dimensions are useful when we are setting up the range for our scale function. This function will map the smallest data point to the 0px of the x-axis and the biggest temperature to the chartWidth.

const xScale = d3.scaleLinear()
  .domain(d3.extent(dataset, d => d.temperature))
  .range([0,chartWidth])

It is a little bit confusing for the y-axis because the SVG coordinate the (0,0) starts at the top left, so it’s the opposite in the range while mapping our minimum and maximum data points for the y-axis.

const yScale = d3.scaleLinear()
  .domain(d3.extent(dataset, d => d.temperature))
  .range([chartHeight, 0])

We also see a transform function to move our chart area to the correct position using margin values.

const g = svg.append("g")
  .attr("transform", `translate(${margin.left}, ${margin.top})`)

Leave a comment