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} )
Related
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.
I am trying to create a map visualization using d3.
I have gotten the map to work and am trying to add points on the map.
Depending on some other data in the CSV file (inspection results) I want certain points to have a different color.
I can add the points using this code, but I cannot get the colors to come out correctly (there should be red ones, but all of them are green). I think it is a problem with how I'm trying to get the data out, or just a problem with my JavaScript in general. Any help would be appreciated. Thank you!
function colorr(d) {
if (d == 0) {
return "red";
} else {
return "green";
}
}
var dataset = []
// load data about food
// https://stackoverflow.com/questions/47821332/plot-points-in-map-d3-javascript
// https://groups.google.com/forum/#!topic/d3-js/AVEa7nPCFAk
// https://stackoverflow.com/questions/10805184/show-data-on-mouseover-of-circle
d3.csv('data6.csv').then( function(data) {
// don't know if this actually does anything...
dataset=data.map(function(d) { return [+d["InspectionScore"],+d["Longitude"],+d["Latitude"]];});
g.selectAll('circle')
.data(data)
.enter()
.append('circle')
.attr("cx",function(d) { return projection([d.Longitude,d.Latitude])[0]; }).merge(g)
.attr("cy",function(d) { return projection([d.Longitude,d.Latitude])[1]; }).merge(g)
.attr("r", .4)
.attr("fill", d3.color(colorr( function(d) { return d.InspectionScore } ) ));
});
This can be resolved by changing the last line to:
.attr("fill", d => d3.color(colorr(d.InspectionScore))));
The reason this works is that d3's attr allows you to take the attribute value from a function. In this case you want to transform the data element to either red or blue. This is what the arrow function does in the above code. It is equivalent to :
.attr("fill", function(d) {
return d3.color(colorr(d.InspectionScore));
})
To get a deeper understanding of how D3 works, you can check the tutorials.
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; });
});
I have two array objects that hold my d3.svg.symbol types which are circles, squares & triangles. Array #1 has multiple symbols which I plot across the canvas, whereas array #2 only holds three symbols aligned together.
My goal is to be able to click on array #2 to filter out all of the array #1 symbols that i dont want to see. e.g. Clicking a circle in array #2 would only mean circles are shown in array #1.
var array1 = svg.selectAll(a.array1)
.data(json).enter().append("a")
array1.transition().duration(1000)
.attr("transform", function(d,i) {return "translate("+d.x+","+d.y+")" ;})
array1.append('path')
.attr("d", d3.svg.symbol().type(function(d) {return shape [d.Country];}).size(120))
var array2 = svg.selectAll(g.array2)
.data(filt)
.enter().append("g")
.attr("transform", function(d,i) {return "translate("+d.x+","+d.y+")" ;})
array2.append("path")
.attr("d", d3.svg.symbol().type(function(d){return d.shape;}).size(200))
.attr("transform", "translate(-10, -5)")
So my query is how do I specify the click onto array#2 specific types as I have three. Therefore, I would like all to be clickable, but have a different outcome.
So far I have tried this just to try & select specific shapes in array#2
array2.on("click", function(){ alert('success') })
which just alerts when I click any of them, however when this is applied:
array2.on("click", function(){ if (d3.svg.symbol().type('circle') === true) { return alert('success') ;}; })
When I click the circle of array2 it doesnt alert at all.
It would be great if I could get some help - thanks. http://jsfiddle.net/Zc4z9/16/
The event listener gets the current datum and index as arguments, see the documentation. You can also access the DOM element through this. You could use this like follows.
.on("click", function(d) {
if(d.shape == "circle") { alert("success"); }
});
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.