...

/

Applying Scales to Visualizations

Applying Scales to Visualizations

We are going to apply the ‘scaleLinear()’ function to transform the data into coordinates for drawing the scatter plot.

It is time to apply our knowledge of scales to the scatter plot we have been building. There are four properties we can change on the circle. They are the x coordinate, y coordinate, color, and size. We are going to focus on the coordinates. The x position of a circle will represent humidity, and the y position will represent the temperature.

What to transform?

We are going to transform the x and y coordinates. The question is, what are we going to transform them to? The coordinates for any circle should stay within the bounds of the container we drew in our image. We must draw them in the container. The purpose of the container was to prevent a shape from appearing on the edge of the image. If that happened, the shape would be cut off.

We want to transform the x coordinate of a shape between 0 and the width of the container. The y coordinate of a shape should be between 0 and the height of the container. Now that we know what we will transform our data to let’s create scales that will transform our values.

Creating the scales

We are going to create the scales before drawing the circles. In the draw() function, we will add the following:

Press + to interact
async function draw() {
// Data
const dataset = await d3.json('/udata/1kL2GBJw8VB/data-4-1.json')
const xAccessor = (d) => d.currently.humidity
const yAccessor = (d) => d.currently.apparentTemperature
// Dimensions
let dimensions = {
width: 800,
height: 800,
margin: {
top: 50,
right: 50,
bottom: 50,
left: 50
}
}
// Draw Image
const svg = d3.select("#chart")
.append("svg")
.attr("width", dimensions.width)
.attr("height", dimensions.height)
const ctr = svg.append("g") // <g>
.attr(
"transform",
`translate(${dimensions.margin.left}, ${dimensions.margin.top})`
)
// Scales
const xScale = d3.scaleLinear()
.domain(d3.extent(dataset, xAccessor))
.range([0, dimensions.ctrWidth])
// Draw circles
ctr.selectAll('circle')
.data(dataset)
.join('circle')
.attr("cx", xAccessor)
.attr("cy", yAccessor)
.attr("r", 5)
.attr("fill", 'red')
}
draw()

There is a comment that says “Scales.” Below this comment, we are creating a scale called xScale. Its value is the d3.scaleLinear() function.

This method will create the initial scale function. The scale will always return the original value. We need to tell it the original range, which is called the input domain. We can set the input domain by chaining the domain() function.

 ...