Why is domain not using d3.max(data) in D3? - d3.js

I'm new to D3 and playing around with a scatterplot. I cannot get d3.max(data) to work correctly in setting up domain!
I have the following setting up a random dataset:
var data = [];
for (i=0; i < 40; i++){
data.push({"x": i/40, "y": i/8, "a": Math.floor(Math.random() * 3), "x2": Math.random()});
}
And then the following to set my coordinates:
var x = d3.scale.linear().domain([0, 1]).range([0 + margin, w-margin]),
y = d3.scale.linear().domain([0, d3.max(data)]).range([0 + margin, h-margin]),
c = d3.scale.linear().domain([0, 3]).range(["hsl(100,50%,50%)", "rgb(350, 50%, 50%)"]).interpolate(d3.interpolateHsl);
This puts all 40 points in a single, horizontal line. If I replace d3.max(data) with '5' then it is a diagonal (albeit from the upper left to the bottom right, I'm still struggling to flip y-coordinates). Why isn't d3.max(data) working as expected?

d3.max() expects an array of numbers, not of objects. The elements of data have an internal key-value structure and there is no way for d3.max() to know what to take the maximum of. You can use something like jQuery's $.map to get the elements of the objects you want and then take the max, e.g.
var maxy = d3.max($.map(data, function(d) { return d.y; }));
Edit:
As pointed out in the comment below, you don't even need JQuery for this, as .map() is a native Array method. The code then becomes simply
var maxy = d3.max(data.map(function(d) { return d.y; }));
or even simpler (and for those browsers that don't implement Array.map()), using the optional second argument of d3.max that tells it how to access values within the array
var maxy = d3.max(data, function(d) { return d.y; });

d3.max API documentation can be found here.
# d3.max(array[, accessor])
Returns the maximum value in the given array using natural order. If
the array is empty, returns undefined. An optional accessor function
may be specified, which is equivalent to calling array.map(accessor)
before computing the maximum value. Unlike the built-in Math.max, this
method ignores undefined values; this is useful for computing the
domain of a scale while only considering the defined region of the
data. In addition, elements are compared using natural order rather
than numeric order. For example, the maximum of ["20", "3"] is "3",
while the maximum of [20, 3] is 20.
Applying this information to the original question we get:
function accessor(o){
return o.y;
}
var y = d3.scale.linear()
.domain([0, d3.max(data, accessor)])
.range([0 + margin, h-margin]);
If you end up using many accessor functions you can just make a factory.
function accessor(key) {
return function (o) {
return o[key];
};
}
var x = d3.scale.linear()
.domain([0, d3.max(data, accessor('x'))])
.range([...]),
y = d3.scale.linear()
.domain([0, d3.max(data, accessor('y'))])
.range([...]);

I was having a similar issue dealing with an associative array. My data looked like the following: [{"year_decided":1982,"total":0},{"year_decided":"1983","Total":"847"},...}]
Simply passing parseInt before returning the value worked.
var yScale = d3.scale.linear()
.domain([0, d3.max(query,function(d){ return parseInt(d["Total"]); }) ])
.range([0,h]);

Related

Violin plot in d3

I need to build a violin point with discrete data points in d3.
Example:
I am not sure how to align the center for each value on X axis. The default behavior will overlay all the points with same X and Y value, however I would like the points to be offset while being center aligned e.g. 5.1 has 3 values in control group and 4.5 has 2 values, all center aligned. It is easy to do so for either right or left aligned by doing a transformation of each point by a specified amount. However, the center alignment seems to be quite hacky.
A hacky way would be to manually transform the X value by maintaining a couple of arrays to see whether this is the first, even or odd number of element and place it according my specifying the value. Is there a proper way to handle this?
The only example of violin plot in d3 I found was here - which implements a probability distribution rather than the discrete values which I require.
"A hacky way would be to manually transform the X value by maintaining a couple of arrays" - that's pretty much the way most d3 layouts work :-) . Discretise your data set by the y value (weight), keeping a total of the data points in each discrete group and a group index for each datum. Then use those to calculate offsets x-ways and the rounded y-value.
See https://jsfiddle.net/n444k759/4/
// below code assumes a svg and g group element are present (they are in the jsfiddle)
var yscale = d3.scale.linear().domain([0,10]).range([0,390]);
var xscale = d3.scale.linear().domain([0,2]).range ([0,390])
var color = d3.scale.ordinal().domain([0,1]).range(["red", "blue"]);
var data = [];
for (var n = 0; n <100; n++) {
data.push({weight: Math.random() * 10.0, category: Math.floor (Math.random() * 2.0)});
}
var groups = {};
var circleR = 5;
var discreteTo = (circleR * 2) / (yscale.range()[1] / yscale.domain()[1]);
data.forEach (function(datum) {
var g = Math.floor (datum.weight / discreteTo);
var cat = datum.category;
var ref = cat+"-"+g;
if (!groups[ref]) { groups[ref] = 0; }
datum.groupIndex = groups[ref];
datum.discy = yscale (g * discreteTo); // discrete
groups[ref]++;
});
data.forEach (function(datum) {
var cat = datum.category;
var g = Math.floor (datum.weight / discreteTo);
var ref = cat+"-"+g;
datum.offset = datum.groupIndex - ((groups[ref] - 1) / 2);
});
d3.select("svg g").selectAll("circle").data(data)
.enter()
.append("circle")
.attr("cx", function(d) { return 50 + xscale(d.category) + (d.offset * (circleR * 2)); })
.attr("r", circleR)
.attr("cy", function(d) { return 10 + d.discy; })
.style ("fill", function(d) { return color(d.category); })
;
The above example discretes into groups according to the size of the display and the size of the circle to display. You might want to discrete by a given interval and then work out the size of circle from that.
Edit: Updated to show how to differentiate when category is different as in your screenshot above

Creating unique scales for parallel coordinates using d3 (multivariate)

I'm trying to find a way to assign different scale max/min to different columns of my data using parallel coordinates. I've adopted code from http://bl.ocks.org/jasondavies/1341281 but do not want to use d3.extent. I've tried different methods (for loops, if statements) but d3 doesn't seem to like that.
Any ideas for how I should approach this?
d3.json("HW3/scores.json", function(error, scores){
x.domain(dimensions = d3.keys(scores[0]).filter(function(d){
return d != "Country" && (y[d] = d3.scale.linear()
.domain(d3.extent(scores, function(p) { return +p[d]; }))
.range([height, 0]));
}));
I'm trying to change the domains of 6 scales (pulled from scores.json, all numbers in column format) to be unique to the data type:
percent (columns 1 and 6) should be from 1 - 100,
score (columns 3 and 4) should be from 200 - max of both score
columns,
hours (columns 2 and 5) should be from 0 - max of both hour columns.
Please and Thank You for ANY help you can provide to a d3 n00b.
You can simply remove the code that creates the scales from the filter function and create the y scales manually according to your specification:
x.domain(dimensions = d3.keys(data[0]).filter(function(d) {
return d != "name";
}));
y['percent 1'] = d3.scale.linear()
.domain([1, 100])
.range([height, 0]));
y['hours 1'] = d3.scale.linear()
.domain([0, d3.max(data, function(p) { return Math.max(+p['hours 1'], +p['hours 2']); }])
.range([height, 0]));
// etc

Inversion with ordinal scale

Is there any way to find inversion of ordinal scale?
I am using string value on x axis which is using ordinal scale and i on mouse move i want to find inversion with x axis to find which string is there at mouse position?
Is there any way to find this?
var barLabels = dataset.map(function(datum) {
return datum.image;
});
console.log(barLabels);
var imageScale = d3.scale.ordinal()
.domain(barLabels)
.rangeRoundBands([0, w], 0.1);
// divides bands equally among total width, with 10% spacing.
console.log("imageScale....................");
console.log(imageScale.domain());
.
.
var xPos = d3.mouse(this)[0];
xScale.invert(xPos);
I actually think it doesn't make sense that there isn't an invert method for ordinal scales, but you can figure it out using the ordinal.range() method, which will give you back the start values for each bar, and the ordinal.rangeBand() method for their width.
Example here:
http://fiddle.jshell.net/dMpbh/2/
The relevant code is
.on("click", function(d,i) {
var xPos = d3.mouse(this)[0];
console.log("Clicked at " + xPos);
//console.log(imageScale.invert(xPos));
var leftEdges = imageScale.range();
var width = imageScale.rangeBand();
var j;
for(j=0; xPos > (leftEdges[j] + width); j++) {}
//do nothing, just increment j until case fails
console.log("Clicked on " + imageScale.domain()[j]);
});
I found a shorter implementation here in this rejected pull request which worked perfectly.
var ypos = domain[d3.bisect(range, xpos) - 1];
where domain and range are scale domain and range:
var domain = x.domain(),
range = x.range();
I have in the past reversed the domain and range when this is needed
> var a = d3.scale.linear().domain([0,100]).range([0, w]);
> var b = d3.scale.linear().domain([0,w]).range([0, 100]);
> b(a(5));
5
However with ordinal the answer is not as simple. I have checked the documentation & code and it does not seem to be a simple way. I would start by mapping the items from the domain and working out the start and stop point. Here is a start.
imageScale.domain().map(function(d){
return {
'item':d,
'start':imageScale(d)
};
})
Consider posting your question as a feature request at https://github.com/mbostock/d3/issues?state=open in case
There is sufficient demand for such feature
That I haven't overlooked anything or that there is something more hidden below the documentation that would help in this case
If you just want to know which mouse position corresponds to which data, then d3 is already doing that for you.
.on("click", function(d,i) {
console.log("Clicked on " + d);
});
I have updated the Fiddle from #AmeliaBR http://fiddle.jshell.net/dMpbh/17/
I recently found myself in the same situation as OP.
I needed to get the inverse of a categorical scale for a slider. The slider has 3 discrete values and looks and behaves like a three-way toggle switch. It changes the blending mode on some SVG elements. I created an inverse scale with scaleQuantize() as follows:
var modeArray = ["normal", "multiply", "screen"];
var modeScale = d3.scalePoint()
.domain(modeArray)
.range([0, 120]);
var inverseModeScale = d3.scaleQuantize()
.domain(modeScale.range())
.range(modeScale.domain());
I feed this inverseModeScale the mouse x-position (d3.mouse(this)[0]) on drag:
.call( d3.drag()
.on("start.interrupt", function() { modeSlider.interrupt(); })
.on("start drag", function() { inverseModeScale(d3.mouse(this)[0]); })
)
It returns the element from modeArray that is closest to the mouse's x-position. Even if that value is out of bounds (-400 or 940), it returns the correct element.
Answer may seem a bit specific to sliders but posting anyway because it's valid (I think) and this question is in the top results for " d3 invert ordinal " on Google.
Note: This answer uses d3 v4.
I understand why Mike Bostock may be reluctant to include invert on ordinal scales since you can't return a singular true value. However, here is my version of it.
The function takes a position and returns the surrounding datums. Maybe I'll follow up with a binary search version later :-)
function ordinalInvert(pos, scale) {
var previous = null
var domain = scale.domain()
for(idx in domain) {
if(scale(datum[idx]) > pos) {
return [previous, datum[idx]];
}
previous = datum[idx];
}
return [previous, null];
}
I solved it by constructing a second linear scale with the same domain and range, and then calling invert on that.
var scale = d3.scale.ordinal()
.domain(domain)
.range(range);
var continousScale = d3.scale.linear()
.domain(domain)
.range(range)
var data = _.map(range, function(i) {
return continousScale.invert(i);
});
You can easily get the object's index/data in callback
.on("click", function(d,i) {
console.log("Clicked on index = " + i);
console.log("Clicked on data = " + d);
// d == imageScale.domain()[1]
});
d is the invert value itself.
You don't need to use obj.domain()[index] .

Using d3.js is there a way to zero align two Y Axes with positive and negative values

I am new to d3, learning a lot. I have an issue I cannot find an example for:
I have two y axes with positive and negative values with vastly different domains, one being large dollar amounts the other being percentages.
The resulting graph from cobbling together examples looks really awesome with one slight detail, the zero line for each y axis is in a slightly different position. Does anyone know of a way in d3 to get the zero line to be at the same x position?
I would like these two yScales/axes to share the same zero line
// define yScale
var yScale = d3.scale.linear()
.range([height, 0])
.domain(d3.extent(dataset, function(d) { return d.value_di1; }))
;
// define y2 scale
var yScale2 = d3.scale.linear()
.range([height, 0])
.domain(d3.extent(dataset, function(d) { return d.calc_di1_di2_percent; }))
;
Here is a link to a jsfiddle with sample data:
http://jsfiddle.net/jglover/XvBs3/1/
(the x-axis ticks look horrible in the jsfiddle example)
In general, there's unfortunately no way to do this neatly. D3 doesn't really have a concept of several things lining up and therefore no means of accomplishing it.
In your particular case however, you can fix it quite easily by tweaking the domain of the second y axis:
.domain([d3.min(dataset, function(d) { return d.calc_di1_di2_percent; }), 0.7])
Complete example here.
To make the 0 level the same position, a strategy is to equalize the length/proportion of the y axes.
Here are the concepts to the solution below:
The alignment of baseline depends on the length of the y axes.
To let all value shown in the bar, we need to extend the shorter side of the dimension, which compares to the other, to make the proportion of the two axes equal.
example:
// dummy data
const y1List = [-1000, 120, -130, 1400],
y2List = [-0.1, 0.2, 0.3, -0.4];
// get proportion of the two y axes
const totalY1Length = Math.abs(d3.min(y1List)) + Math.abs(d3.max(y1List)),
totalY2Length = Math.abs(d3.min(y2List)) + Math.abs(d3.max(y2List)),
maxY1ToY2 = totalY2Length * d3.max(y1List) / totalY1Length,
minY1ToY2 = totalY2Length * d3.min(y1List) / totalY1Length,
maxY2ToY1 = totalY1Length * d3.max(y2List) / totalY2Length,
minY2ToY1 = totalY1Length * d3.min(y2List) / totalY2Length;
// extend the shorter side of the upper dimension with corresponding value
let maxY1Domain = d3.max(y1List),
maxY2Domain = d3.max(y2List);
if (maxY1ToY2 > d3.max(y2List)) {
maxY2Domain = d3.max(y2List) + maxY1ToY2 - d3.max(y2List);
} else {
maxY1Domain = d3.max(y1List) + maxY2ToY1 - d3.max(y1List);
}
// extend the shorter side of the lower dimension with corresponding value
let minY1Domain = d3.min(y1List),
minY2Domain = d3.min(y2List);
if (minY1ToY2 < d3.min(y2List)) {
minY2Domain = d3.min(y2List) + minY1ToY2 - d3.min(y2List);
} else {
minY1Domain = d3.min(y1List) + minY2ToY1 - d3.min(y1List);
}
// finally, we get the domains for our two y axes
const y1Domain = [minY1Domain, maxY1Domain],
y2Domain = [minY2Domain, maxY2Domain];

scale.linear() is returning NaN

Im running a simple bar chart using d3.scale.linear() and hardcoding he domain range for this example
I can see in firebug that when aplying attr of width to my div, w_bar appears to be NaN.
Why is that?
var w_bar = d3.scale.linear()
.domain([0, 107525233]) //harcoded
.range(["0px", "290px"]);
var theList = d3.select("#list").selectAll("div")
.data(myJSON);
theList.enter().append("div")
.text(function (d) { return d.v; })
.transition()
.duration(1000)
.attr("width", w_bar); // Why NaN?
theList.exit()
.remove();
Here's the jsfiddle:
http://jsfiddle.net/NAhD9/5/
Well, w_bar is Not a Number, and the width attribute needs to be a number. Hence, NaN.
If you want your width attribute to scale based on the v attribute in your myJSON object, you should say
.attr("width",function (d) {return w_bar(d.v)}).
This is how scales work in d3, they are a function which takes in an argument (some value within the domain of the scale) and returns that value transformed to fit into the range of your scale.
Updated jsFiddle here.
You need to use a function to tell d3 how you want your data to interact with to scale to create an array:
.attr("width", function(d){ return w_bar(d.v); })
This will take all the v attributes from objects making up the myJSON array, scale them with w_bar, and set the width of their corresponding rectangles equal to that value.

Resources