D3#6 Generic direction on addressing Map data structures in arrow functions - javascript

Have an Observable using D3 v6 and am starting to use the Map data structure. While it seems array-based I am having difficulty translating how to get to different parts of maps in arrow functions.
I have a data set shaped:
dataByHub = Map(2) {
"ST" => Array(19) [Object, Object, Object... ]
"FING" => Array(27) [Object, Object, Object ...]
A log of the data going into the function to generate the path looks like:
data
Pn {_groups: Array(2), _parents: Array(2)}
_groups: (2) [Array(19), Array(27)]
_parents: (2) [g#ST.hub, g#FING.hub]
__proto__: Object
...and, for each hub (_parents which determines my y_hub), I want to iterate over the appropriate Array (_group) and pass in the sets of Xs to a function to create a path. The result should be a line with variable length spaces and dashes representing disconnection events.
What I have...
The D3 portion looks like, where I want to attach the Xs from a hub to a path:
d3.select("#hubs").selectAll(".hub")
.data(dataByHub)
.enter().append("g")
.attr("class", "hub")
.attr("id", d => d[0])
.selectAll("path")
.data((d,i) => d[1])
.join("path")
.call(log,"data")
.style("stroke", "black")
.style("fill", "none")
.attr("d", (d,i) => segment(d.Xs,i))
Which uses segment() to generate the path:
function segment(data, hub) {
const p = d3.path();
console.log("segment", data); //data.Xs[0]
const y_hub = hub * 100;
p.moveTo(data.Xs[0],y_hub);
p.lineTo(data.Xs[1],y_hub);
p.closePath();
// console.log("p", p);
return p.toString();
}
I have tried different setups for the .data for the path but either get undefined or an individual pair of Xs's instead of a series of them.

Based on #Robin Mackenzie's question about passing an array or individual pair I refactored the function to accept the array.
So the call became:
.attr("d", (d,i) => events(d[1]) )
However, the important part of the solution was how to get to the elements of the Map. The missing piece was the index into the array after "data" before ".Xs"
function events(data) {
const p = d3.path();
const y_hub = yScale(data[0].Hub);
for (var n=0; n < data.length; n++) {
p.moveTo(xScale(data[n].Xs[0]),y_hub);
p.lineTo(xScale(data[n].Xs[1]),y_hub);
}
p.closePath();
return p.toString();
}
Thanks to my friend Alex Carroll for additional help on Maps.

Related

plotting graph symbols using two-level nested data in d3.js

I am trying to replicate this example of a multiline chart with dots. My data is basically the same, where I have an object with name and values in the first level, and then a couple of values in the second level, inside values. The length of the arrays inside values is 40.
Now, one requirement is that all the dots for all the paths are inside the same g group within the DOM. This is giving me a lot of trouble because I can't seem to figure out how to join the circles with the appropriate portion of the nested data.
The last thing I've tried is this:
var symbolsb = d3.select("#plot-b") // plot-b is the graph area group within the svg
.append("g")
.attr("id", "symbols-b");
symbolsb.selectAll("circle")
.data(games, function(d) {console.log(d.values) // games is my data object
return d.values})
.enter()
.append("circle")
.attr("class", "symbolsb")
.attr("cx", function(d,i) {console.log(d)
return x(d.values.date);})
.attr("cy", function(d,i) {return y_count(d.count);})
.attr("r", function(d,i) {
let parent = this.parentNode;
let datum = d3.select(parent).datum();
console.log(parent)
if (i%3 === 1 && included_names.includes(datum[i].name)) {
return 8;}
else {return null;}})
.style("fill", function(d,i) {
let parent = this.parentNode;
let datum = d3.select(parent).datum();
{return color(datum.name);}});
As I (incorrectly) understand the data() function, I thought that by returning d.values, the functions in cx, cy, and r would just see the array(s) that is inside d.values, but when log d to the console within the functions to define cx, cy, etc. I see again the full object games. Again, I though I should only get the values portion of the object.
I have been able to get a plot that looks like the result I want by loading the data and appending a g when defining symbolsb, but this creates a group for each set of circles.
I think the problem comes from my confusion of how nested objects are accessed by the data() function. So any help explaining that would be greatly appreciated.
It would be great if you could provide a live reproduction, for example in an Observable or VizHub notebook.
This line looks suspect
.data(games, function(d) {console.log(d.values) // games is my data object
return d.values})
The second argument to *selection*.data should be a 'key function', a function that returns a unique string identifier for each datum. Here you are giving an object (d.values) which will get stringified to [object Object] for each data point. This also explains why you're seeing the full games object when logging. I think it's safe here to just remove the second argument to .data():
.data(games)
This also doesn't look right
.attr("r", function(d,i) {
let parent = this.parentNode;
let datum = d3.select(parent).datum();
console.log(parent)
if (i%3 === 1 && included_names.includes(datum[i].name)) {
return 8;}
else {
return null;
*emphasized text*}})
I'm not entirely sure what you're trying to do here. If you're trying to access the name of the data point you can just access it on the data point itself using .attr("r", function(d,i) { if (included_names.includes(d.name)) { return 8 } else { return 0} )

D3: How to conditionally bind SVG objects to data?

I have here an array of objects that I'm visualising using D3. I bind each object to a group element and append to that an SVG graphic that depends on some object property, roughly like this:
var iconGroups = zoomArea.selectAll("g.icons")
.data(resources)
.enter()
.append("g")
var icons = iconGroups.append(function(d){
if(d.type == "Apple"){
return appleIcon;
}else if(d.type == "Orange"){
return orangeIcon;
})
etc. Now I'd like to extend some of those icons with an additional line. I could add a line element for each data point and set them visible only where applicable, but since I want to add them only for say one out of a hundred data points, that seems inefficient. Is there a way to bind SVG lines to only those objects where d.type == "Apple"?
I would create separate selections for icons and lines, this way:
var iconGroups = zoomArea.selectAll('g.icons')
.data(resources);
iconGroups
.enter()
.append('g')
.classed('icons', true);
iconGroups.exit().remove();
var icons = iconGroups.selectAll('.icon').data(function(d) {return [d];});
icons
.enter()
.append(function(d) {
if(d.type === 'Apple'){
return appleIcon;
}else if(d.type === 'Orange'){
return orangeIcon;
}
}).classed('icon', true);
icons.exit().remove();
var lines = iconGroups.selectAll('.line').data(function(d) {
return d.type === 'Apple' ? [d] : [];
});
lines
.enter()
.append('line')
.classed('line', true);
lines.exit().remove();
.exit().remove() is added just because I add it always to be sure that updates work better. :)
Maybe the code is longer than .filter() but I use the following structure all the time and it's easier to scale it.
edit: apropos comment - If you need to pass indexes, you should pass them in binded data:
var iconGroups = zoomArea.selectAll('g.icons')
.data(resources.map(function(resource, index) {
return Object.create(resource, {index: index})
}));
(Object.create() was used just to not mutate the data, you can use _.clone, Object.assign() or just mutate it if it does not bother you)
then you can access it like:
lines.attr("x1", function(d){ console.log(d.index);})
You could add a class to the icons to be selected (e.g. appleIcon), and use that class in a selector to add the lines.
Use d3 filter.
selection.filter(selector)
Filters the selection, returning a new selection that contains only the elements for which the specified selector is true.
Reference: https://github.com/mbostock/d3/wiki/Selections#filter
Demo: http://bl.ocks.org/d3noob/8dc93bce7e7200ab487d

dc.js - multiple lineChart based on separate categories in single csv file

For example if I have the following csv file:
category, number, total
A,1,3
A,2,5
A,3,1
B,1,4
B,2,6
B,3,1
C,1,5
C,2,2
C,3,4
I was able to follow the following example and separate out the data into different csv files and composing each one.
github link
However, I was wondering how would I recreate the same lineCharts if I were to only have a single csv file and separate each lineChart by each grouped category.
Thanks.
#minikomi's answer is the straight d3 way to do this.
The dc.js/crossfilter way to do this (if you want your charts to reduce values for each key and interact/filter with other dc charts) is to reduce multiple values in a single group like this:
var group = dimension.group().reduce(
function(p, v) { // add
p[v.type] = (p[v.type] || 0) + v.value;
return p;
},
function(p, v) { // remove
p[v.type] -= v.value;
return p;
},
function() { // initial
return {};
});
https://github.com/dc-js/dc.js/wiki/FAQ#rows-contain-a-single-value-but-a-different-value-per-row
Then you can specify each line chart by passing the group along with an accessor to the .group method like so:
lineChartA.group(group, 'A', function(a) { return x.A; })
lineChartB.group(group, 'B', function(a) { return x.B; })
If you want to combine the line charts in a single chart, you can compose them with the composite chart or series chart
You can reduce the data to give 3 different arrays, each which only contain data from each category:
var grouped = data.reduce(function(o,d) {
if(o[d.category]) {
o[d.category].push(d);
} else {
o[d.category] = [d];
}
return o;
}, {});
Usually in d3 we work with arrays of data, so I'd use d3.map to convert it to an array of pairs key / value
var lineData = d3.map(grouped).entries()
Now, you can use this to create your lines (leaving out creating scales x and y), svg element etc.:
var line = d3.svg.line()
.x(function(d){return x(d.number)})
.y(function(d){return y(d.total)})
var linesGroup = svg.append("g")
var lines = linesGroup.data(lineData).enter()
.append("line")
.attr("d", function(d){return line(d.value)})
You could also set the stroke color using the d.key for the d3.map entries (which will come from the key we used in the reduce step - the category). Don't forget to convert your csv data to numbers too using parseInt().

How to add links from CSV file to SVG elements generated with D3?

I am in a bit of a bind and need some with help with linking my svg elements with URL's contained in an CSV file. I have a symbols map with over 100 symbols. The symbols are based on coordinates pulled from longitude and latitude in a CSV file which also contains the links that I would like each unique symbol to link to. I know there is an easy way to do this, pretty sure I'm overlooking the solution.
My CSV file is as follows:
name,longitude,latitude,city,state,url
College of Charleston,803,342,Charleston,SC,http://sitename.com/colleges/college-of-charleston/
etc...
My symbols are generated using D3 and placed on top of my SVG map. I am also using D3 to wrap the symbols in anchor tags. I simply want these anchor tags to link to the appropriate url that correlates with the latitude and longitudes of that particular symbol.
/* Start SVG */
var width = 960,
height = 640.4,
positions = [],
centered;
var bodyNode = d3.select('#Map').node();
var list = $('.school-list').each(function(i){});
var svg = d3.select("#Map");
var contain = d3.select("#map-contain");
var circles = svg.append("svg:g")
.attr("id", "circles");
var g = d3.selectAll("g");
// var locationBySchools = {};
d3.csv("http://sitename.com/wp-content/themes/vibe/homepage/schools.csv",function(schools){
schools = schools.filter(function(schools){
var location = [+schools.longitude, +schools.latitude];
// locationBySchools[schools.loc] = location;
positions.push(location);
return true;
});
circles.selectAll("circles")
.data(schools)
.enter().append("svg:a")
.attr("xlink:href", function(d) { })
.append("svg:circle")
.attr("cx", function(d,i) {return positions[i][0]})
.attr("cy", function(d,i) {return positions[i][1]})
.attr("r", function(d,i) {return 6})
.attr("i", function(d,i) {return i})
.attr("class", "symbol")
Really stuck with this one...Any ideas?
The short answer is that you should simply return the url property from your data when you are assigning the xlink:href attribute:
.attr("xlink:href", function(d) { return d.url; })
However, there are a couple other issues with the code you posted.
Issue 1. circles.selectAll('circles')
This starts with a the selection of your g element, and within it, selects all elements with the tag-name circles. The problem is that circles is not a valid svg tag. This just creates an empty selection, which is okay in this case because the selection is only being used to create new elements. But, it's a bad habit to make dummy selections like this, and it can be confusing to others trying to understand your code. Instead, you should decide on a class name to give to each of the new link elements, and use that class name to make your selection. For example, if you decide to give them a class of link you would want to do the following:
First create a selection for all of the elements with class="link":
circles.selectAll('.link')
This selection will initially be empty, but when you use .data() to bind your data to it, it will be given an enter selection which you can use to create the new elements. Then you can add the class of link to the newly created elements:
.data(schools).enter().append('svg:a')
.attr('class', 'link')
Issue 2. .attr("i", function(d,i) {return i})
This one's pretty straightforward, there is no such attribute as i on svg elements. If you want to store arbitrary data on an element to be able to access it later, you can use a data attribute. In this case you might want to use something nice and semantic like data-index.
Issue 3. positions.push(location)
This is a big one. I would not recommend that you make a separate array to store the altered values from your dataset. You can use an accessor function in your d3.csv() function call, and clean up the incoming data that way. It will save you from having to maintain consistent data across two separate arrays. The accessor function will iterate over the dataset, taking as input the current datum, and should return an object representing the adjusted datum that will be used. This is a good spot to use your unary operator to coerce your latitude and longitude:
function accessor(d) {
return {
name: d.name,
longitude: +d.longitude,
latitude: +d.latitude,
city: d.city,
state: d.state,
url: d.url
};
}
There are two different ways to hook the accessor function into your d3.csv() call:
Method 1: Add a middle parameter to d3.csv() so that the parameters are (<url>, <accessor>, <callback>):
d3.csv('path/to/schools.csv', accessor, function(schools) {
// ...etc...
});
Method 2: Use the .row() method of d3.csv()
d3.csv('path/to/schools.csv')
.row(accessor)
.get(function(schools) {
// ...etc...
});
Now when you want to access the latitude and longitude in your preferred format, you can get them right from the bound data, instead of from an outside source. This keeps everything clean and consistent.
Putting all of this together, you get the following:
d3.csv('http://sitename.com/wp-content/themes/vibe/homepage/schools.csv')
// provide the accessor function
.row(function accessor(d) {
return {
name: d.name,
longitude: +d.longitude,
latitude: +d.latitude,
city: d.city,
state: d.state,
url: d.url
};
})
// provide a callback function
.get(function callback(schools) {
circles.selectAll('.link')
.data(schools)
.enter().append('svg:a')
.attr('class', 'link')
// point the link to the url from the data
.attr('xlink:href', function(d) { return d.url; })
.append('svg:circle')
.attr('class', 'symbol')
// now we can just use longitude and latitude
// since we cleaned them up in the accessor fn
.attr('cx', function(d) { return d.longitude; })
.attr('cy', function(d) { return d.latitude; })
// constants can be assigned directly
.attr('r', 6)
.attr('data-index', function(d,i) { return i; });
});

D3js sorting issue on transition applied

I have a dataset already binded to svg:g via a d.id
var categorized = g1.selectAll("g.node")
.data(dataset, function(d){return d.id})
.classed('filtered', false);
categorized.enter()
.append("g")
.attr("class", "node")
...
I use a function to order it from a data value like this:
var sorted = dataset
.filter(function(d) { return d.notation[3].value >=50 } )
.sort(function(a, b) { return d3.descending(a.notation[3].value,
b.notation[3].value) });
It returns the correct order when I console.log it
var filtered = g1.selectAll("g.node")
.data(sorted, function(d) {return d.id})
.classed('filtered', true);
Still in the right order if I console.log it,
but if I apply a delay it reverses the result order
scored.transition()
.delay(500).duration(1000)
.attr("id", function(d) {
console.log(d.id);
});
but keeps it well sorted if I remove the delay.
My question : am I doing something in a bad way?
I think you're observing that d3.js generally uses the "optimized" for loop that iterates in reverse (see Are loops really faster in reverse? among other references).
Would it work to simply reverse your selection? I'm not sure what you're transitioning such that you need the tween steps to be applied in a certain order.

Categories