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?
Chapter 04Ordinal Scales. Unlike continuous, sequential, and quantize scales, ordinal scales work with discrete domains. D3 provides the following ordinal scale generators: d3.
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.
scaleLinear() method is used to create a visual scale point. This method is used to transform data values into visual variables.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With