Histogram Finishing Touches
The histogram will need the proper dimensions, coordinates, and axis to help us read the chart.
We are going to finish the histogram we have been working on before adding some animations. Here is what we will do in this lesson. First, we will adjust the y-coordinate and height for the bars. Second, we will draw an axis to help the reader understand the chart. Lastly, we will add labels to the bars to help identify each bar. The hard part is pretty much over. Adding these features will be relatively easy. Let’s get started.
Dimensions and coordinates
We are going to start with the y coordinate and height of the bars. At the top of the draw()
function, we are going to create an accessor for the y-axis.
// Dataconst dataset = await d3.json('/udata/1kL2GBJw8VB/data-4-1.json')const xAccessor = d => d.currently.humidityconst yAccessor = d => d.length
Histograms measure the frequency within a distribution. It is another way of saying how many times a value appears within a group.
As we saw in the previous lecture, D3 formatted our data by putting the objects into arrays. In JavaScript, arrays have a property called length
, representing the number of items within a group. We are creating an accessor that’ll return the length
of the array. Below the xAccessor
function, we have another variable called yAccessor
. Its value will be an arrow function that accepts the data. We will return the length
property from the data.
Next, let’s create a scale that will transform the length
property into a value that we can use to set the y
and height
attributes for the bars. In the scale section, we are going to create the scale below the bins. Create a variable called yScale
. Its value will ...
Get hands-on with 1400+ tech skills courses.