Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ordinal scale in d3 to return month names

I am trying to use d3.scaleOrdinal() to return corresponding monthNames for a set of data. The month is provided by an integer ranging from 1 to 12 in the original set of data, which can be found here. (I manually added in a monthName field in each datum object)

https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/global-temperature.json

Here is how I am trying to create the scale

var y = d3.scaleOrdinal().range([height, 0]).domain(month);
chart.selectAll('.temp')
       .data(monthlyData)
       .enter().append('rect')
       .attr('class', 'temp')
       .attr('x', function(d){
          return x(new Date(d.year, 0))
       })
       .attr('y', function(d){
          return y(d.monthName)
       })
       .attr('transform', 'translate(30, 0)')
       .attr('width', gridWidth)
       .attr('height', gridHeight)
       .attr('fill', function(d){
           return colorScale(d.variance + data.baseTemperature)
       });

However, I get a really strange result where my data is separated into two bands, one at the top and one all the way at the bottom, which can be seen in this codepen

http://codepen.io/redixhumayun/full/ZBgVax/

How do I do this?

like image 782
random_coder_101 Avatar asked Dec 30 '16 12:12

random_coder_101


People also ask

What is d3 scale ordinal?

Chapter 04Ordinal Scales. Unlike continuous, sequential, and quantize scales, ordinal scales work with discrete domains. D3 provides the following ordinal scale generators: d3.

How does scaleLinear work?

scaleLinear. Linear scales are probably the most commonly used scale type as they are the most suitable scale for transforming data values into positions and lengths. They use a linear function y=mx+c to interpolate across the domain and range.

What is scaleLinear?

scaleLinear() method is used to create a visual scale point. This method is used to transform data values into visual variables.


1 Answers

I think you should use d3.scaleBand (not d3.scaleOrdinal), like this.

A plain ordinal scale expects both its domain and range to be arrays with the same number of discrete elements—the scale then maps them 1-to-1 to each other.

You instead want a scale that maps an array of discrete elements onto a continuous range. For that, a band scale is more suitable.

Alternatively, you could work out at exactly what y value each month should be displayed at, and use that array as your ordinal scale's range, but that's essentially what a band scale does for you internally anyway.

like image 122
Anko Avatar answered Sep 18 '22 22:09

Anko