I am using leaflet and am displaying a json with d3 (vers3) on the map.
Basically I am following this tutorial here.
This is my code. The first callbackHandler describes a method that receives information which another language sends to JavaScript, based on userinteraction with the website.
pathToFile is a link to a file (json) that is then loaded by d3.json(...).
var svg = d3.select(map.getPanes().overlayPane).append("svg"),
g = svg.append("g").attr("class", "leaflet-zoom-hide");
someMethod("myName", function(pathToFile) {
console.log(pathToFile);
d3.json(pathToFile, function(error, collection) {
console.log(collection);
if (error) throw error;
// Use Leaflet to implement a D3 geometric transformation.
function projectPoint(x, y) {
var point = map.latLngToLayerPoint(new L.LatLng(y, x));
this.stream.point(point.x, point.y);
}
var transform = d3.geo.transform({point: projectPoint}),
path = d3.geo.path().projection(transform);
var feature = g1.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("stroke-width", 0.5)
.attr("fill-opacity", 0.7)
.attr("stroke", "white")
map.on("viewreset", reset);
reset();
// Reposition the SVG to cover the features.
function reset() {
var bounds = path.bounds(collection),
topLeft = bounds[0],
bottomRight = bounds[1];
svg1 .attr("width", bottomRight[0] - topLeft[0])
.attr("height", bottomRight[1] - topLeft[1])
.style("left", topLeft[0] + "px")
.style("top", topLeft[1] + "px");
g.attr("transform", "translate(" + -topLeft[0] + "," + -topLeft[1] + ")");
feature.attr("d", path);
}
console.log("1");
});
console.log("2");
});
The funny part is: The first time the code is executed it works fine. My json gets displayed on the map as it should. However, when the first callbackHandler (someMethod) gets executed a second time (upon interaction through some user with the website), the new json does not get displayed on leaflet.
Thats the output of the console.log I included after trying to update the map:
// on startup of website, the callbackHandler "someMethod" gets
./some/path/toFile
Object {crs: Object, type: "FeatureCollection", features: Array[20]}
2
1
// after interaction with the website and execution of the callbackHandler "someMethod"
./some/other/path/toFile
Object {crs: Object, type: "FeatureCollection", features: Array[9]}
2
1
But, the new json does not get displayed. Instead the old one stays.
Why is that?
Since I dont have a code to play around.
My hunch is:
When you first call someMethod the file gets uploaded and everything works fine.
var feature = g1.selectAll("path")
.data(collection.features)
.enter().append("path")
.attr("stroke-width", 0.5)
.attr("fill-opacity", 0.7)
.attr("stroke", "white")
Reason:
First time g1.selectAll("path") runs. The selection is empty and you append path as per the data in the collection.features this will work.
Second time when you do g1.selectAll("path") it will return paths you bind data but append will not work.
So the problem is you need to remove old collection.features or need to update it.
To do that
Option1
var paths = g1.selectAll("path").data()
paths.exit().remove();//remove old data paths
var feature = paths
.enter().append("path")
.attr("stroke-width", 0.5)
.attr("fill-opacity", 0.7)
.attr("stroke", "white")
Option 2 remove all the paths
var paths = g1.selectAll("path").data()
g1.selectAll("path").remove();//remove all paths
var feature = paths
.enter().append("path")
.attr("stroke-width", 0.5)
.attr("fill-opacity", 0.7)
.attr("stroke", "white")
Hope this fixes your problem!
Read update/enter/exit here
Related
I am trying to do the obvious thing of getting the arrowhead colors of my directed graph's links to match the edge colors. Surprisingly I have not found a complete solution for doing this, although this older post seems like an excellent starting point. I would be fine with adapting that solution to work as outlined below, or if there is a superior method for creating arrowheads that achieves this effect I would be most thankful.
First, I have a linear gradient color function to color my edges by property like this:
var gradientColor = d3.scale.linear().domain([0,1]).range(["#08519c","#bdd7e7"]);
Then, like that previous post I have a function for adding markers:
function marker (color) {
var reference;
svg.append("svg:defs").selectAll("marker")
.data([reference])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15) // This sets how far back it sits, kinda
.attr("refY", 0)
.attr("markerWidth", 9)
.attr("markerHeight", 9)
.attr("orient", "auto")
.attr("markerUnits", "userSpaceOnUse")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5")
.style("fill", color);
return "url(#" + reference + ")"; };
And then the links definition I have is this one based on the Curved Links example.
var link = svg.selectAll(".link")
.data(bilinks)
.enter().append("path")
.attr("class", "link")
.style("fill", "none")
.style("opacity", "0.5")
.style("stroke-width", "2")
.style("stroke", function(d) { return gradientColor(d[3]); } )
.attr("marker-end", marker( "#FFCC33" ) );
This DOES NOT work as written; the browser gives me an "Uncaught TypeError: Cannot read property '5' of undefined" (where 'd[5]' refers to the fifth property in a list of properties that the links have). The problem is clearly passing the data function to the marker function in this case. If I feed in a static color like "#FFCC33" then the arrowheads DO change color (now). Unfortunately the person who posted this "marker function" solution 1.5 years ago didn't include the bit about passing the color to the marker function at all.
I don't know how to feed in the link's color properly. Ideally I would be able to use a reference to the color of the link that the arrowhead is attached to rather than inputting the same color function (because eventually I'm going to be coloring the links via different schemes based on button presses).
I've created a JS Fiddle that includes all the necessary bits to see and solve the problem. Currently I'm passing a static color to the markers, but it should be whatever is the color of the link it is attached to. I've also included features for another question on properly positioning the arrowheads and edge tails.
I don't believe you're able to define a single SVG marker and change it's colour. Instead you need to define the marker many times (1 for each colour that you need to use). There's a nice example that recently popped up onto the D3 website.
The way this works, is by having lots if different markers, each defining the colour of the marker. Here's a screenshot of all the markers that are defined:
Then this particular example, cycles the CSS classes on the paths. The particular colored marker that each path is using is defined within the CSS class that's being applied to a path at any given time.
I've modified your example to add a new marker per path (and changed the colors slightly in the gradient to prove that it's working). Here's what I've got:
var width = 960,
height = 500;
var color = d3.scale.category20();
var gradientColor = d3.scale.linear().domain([0, 15]).range(["#ff0000", "#0000ff"]);
var force = d3.layout.force()
.linkDistance(10)
.linkStrength(2)
.size([width, height]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
var defs = svg.append("svg:defs");
d3.json("http://bost.ocks.org/mike/miserables/miserables.json", function (error, graph) {
if (error) throw error;
function marker(color) {
defs.append("svg:marker")
.attr("id", color.replace("#", ""))
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15) // This sets how far back it sits, kinda
.attr("refY", 0)
.attr("markerWidth", 9)
.attr("markerHeight", 9)
.attr("orient", "auto")
.attr("markerUnits", "userSpaceOnUse")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5")
.style("fill", color);
return "url(" + color + ")";
};
var nodes = graph.nodes.slice(),
links = [],
bilinks = [];
graph.links.forEach(function (link) {
var s = nodes[link.source],
t = nodes[link.target],
i = {}, // intermediate node
linkValue = link.value // for transfering value from the links to the bilinks
;
nodes.push(i);
links.push({
source: s,
target: i
}, {
source: i,
target: t
});
bilinks.push([s, i, t, linkValue]);
});
force.nodes(nodes)
.links(links)
.start();
var link = svg.selectAll(".link")
.data(bilinks).enter().append("path")
.attr("class", "link")
.style("fill", "none")
.style("opacity", "0.5")
.style("stroke-width", "2")
.each(function(d) {
var color = gradientColor(d[3]);
console.log(d[3]);
d3.select(this).style("stroke", color)
.attr("marker-end", marker(color));
});
var node = svg.selectAll(".node")
.data(graph.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("circle")
.attr("r", function (d) {
return 2 + d.group;
})
.style("opacity", 0.5)
.style("fill", function (d) {
return color(d.group);
});
node.append("title")
.text(function (d) {
return d.name;
});
force.on("tick", function () {
link.attr("d", function (d) {
return "M" + d[0].x + "," + d[0].y + "S" + d[1].x + "," + d[1].y + " " + d[2].x + "," + d[2].y;
});
node.attr("transform", function (d) {
return "translate(" + d.x + "," + d.y + ")";
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I trying to understand how the D3 chord diagram works. My first step is to display the arcs for the diagram with following script. But for some reason, the arcs are not showing up.
See web page HERE
Can some one tell me what I am missing?
<body>
<script>
// Chart dimensions.
var width = 960,
height = 750,
innerRadius = Math.min(width, height) * .41,
outerRadius = innerRadius * 1.1;
//Create SVG element with chart dementions
var svg = d3. select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append ("g")
.attr("transform", "translate (" + width / 2 + "," + height / 2 + ")");
//------------Reformat Data ------------------------------------------
var matrix = []; // <- here is the data
d3.tsv('picData.tsv', function(err, data)
{
//console.log(data);
pictures = d3.keys(data[0]).slice(1);
//console.log(pictures);
data.forEach(function(row)
{
var mrow = [];
pictures.forEach(function(c)
{
mrow.push(Number(row[c]));
});
matrix.push(mrow);
//console.log(mrow);
});
//console.log('1st row: ' + matrix[0]);
//console.log(matrix);
});
//---------------- Define diagram layout ----------------------------
var chord = d3.layout.chord() //<-- produce a chord diagram from a matrix of input data
.matrix(matrix) //<-- data in matrix form
.padding(0.05)
.sortSubgroups(d3.descending);
var fill = d3.scale.category20(); //<-- https://github.com/mbostock/d3/wiki/API-Reference#d3scale-scales
//console.log(fill);
var g = svg.selectAll("g.group")
.data(chord.groups)
.enter().append("svg:g")
.attr("class", "group");
//console.log(g);
// create arcs
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
//console.log(arc);
g.append("path")
.attr("d", arc)
.style("fill", function(d) { console.log(d.index); return fill(d.index);})
.style("stroke", function(d) { return fill(d.index); })
.attr("id", function(d, i) { return"group-" + d.index });;
g.append("svg:text")
.attr("x", 6)
.attr("class", "picture")
.attr("dy", 15)
.append("svg:textPath")
.attr("xlink:href", function(d) { return "#group-" + d.index; })
.text(function(d) { return pictures[d.index]; });
//console.log(g);
</script>
</body>
Your problem stems from the fact that d3.tsv is asynchronous:
Issues an HTTP GET request for the comma-separated values (CSV) file at the specified url... The request is processed asynchronously.
As a result, all of your code under "Define diagram layout" is being executed before any data is loaded. Otherwise, your code works fine (See image below). So just move all your code into your d3.tsv(...) call and you'll be all set.
Your script is running without errors, but no elements are being created from your data join. That's usually a sign that you are passing in a zero-length data array.
In fact, you're not passing in an array at all; you're passing a function object. When d3 looks up the array length of that object, it returns undefined, which gets coerced to the number zero, and so no groups and no chords are created.
Relevant part of your code:
var g = svg.selectAll("g.group")
.data(chord.groups)
.enter().append("svg:g")
.attr("class", "group");
To actually get the array of chord group data objects, you need to call chord.groups(). Without the () at the end, chord.groups is just the name of the function as an object.
Edited to add:
Ooops, I hadn't even noticed that your drawing code wasn't included inside your d3.tsv callback function. Fix that, as described in mdml's answer, then fix the above.
I have some code on this jsFiddle here that generates a histogram for a data array called "values". That's all well and good.
When I want to update this histogram with a new data array, called "newData", things go wrong. I am trying to adhere to the enter(), update(), exit() D3 strategy (which I am obviously extremely new with). An animation does indeed occur, but as you can see by the fiddle, it just squishes everything into the upper right hand corner. Can someone point out what I am doing wrong in this segment of the code (the update)?
//Animations
d3.select('#new')
.on('click', function(d,i) {
var newHist = d3.layout.histogram().bins(x.ticks(bins))(newData);
var rect = svg.selectAll(".bar")
.data(values, function(d) { return d; });
// enter
rect.enter().insert("g", "g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d) + "," + y(d) + ")"; });
rect.enter().append("rect")
.attr("x", 1)
.attr("width", w)
.attr("height", function(d) { return y(d); });
rect.enter().append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", x(histogram[0].dx) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d); });
// update
svg.selectAll('.bar')
.data(newHist)
.transition()
.duration(3000)
.attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });
svg.selectAll("rect")
.data(newHist)
.transition()
.duration(3000)
.attr("height", function(d) { return height - y(d.y); });
svg.selectAll("text")
.data(newHist)
.transition()
.duration(3000)
.text(function(d) { return formatCount(d.y); });
// exit
rect.exit()
.remove();
});
The entirety of the code is on the JSFiddle linked above. Thanks!
Looking at the code above and the fiddle, a few things jump out at me:
(Line 85) You are still binding the original data
(Lines 105, 115) You are binding the data multiple times
(Line 99) You are still referencing the original histogram variable without updating it with the new data
You are declaring multiple bind/add/update/remove patterns for a single set of (changing) data
You're on the right track, but you need to differentiate between things that need to be updated when the data changes, and things that should not be updated/declared when the data changes. You should only have to declare the d3 pattern (bind, add, update, remove) once... it will work for updated datasets.
So, declare as much as you can outside the makeHist(values) function, and only have code that needs the changed data inside the function (this includes modifying a previously declared scale's domain and range). Then, the on click function can simply call the makeHist function again with the new data.
Here's a rough outline:
// generate data
// declare everything that can be static
// (add svg to dom, declare axes, etc)
// function that handles everything that new data should modify
function makeHist(values) {
// modify domains of axes, create histogram
// bind data
var rect = svg.selectAll('rect')
.data(histogram);
// add new elements
rect.enter().append('rect');
// update existing elements
rect.transition()
.duration(3000)
.attr('transform', '...');
// remove old elements
rect.exit().remove();
}
// generate initial histogram
makeHist(initialValues);
// handle on click event
d3.select('#new')
.on('click', function() {
makeHist(newData);
});
Here's a mostly working updated fiddle, it needs a little bit of cleanup, though:
http://jsfiddle.net/spanndemic/rf4cw/
Spoiler Alert: the two datasets aren't all that different
I'm working with a data set that's categorically identical from year to year, and I want to make a D3 pie chart with animated transitions from year to year. The data is in a 2-d array, each inner array is a year. Because the number of values isn't changing, I think I can just replace the data set for the transition, and I don't need to do a data join (?).
I have the pie chart working well initially, and I'm updating the data via click event. But my transitions aren't working. Here's the code for the first pie chart (there are variable declarations and other data managing that I've left out to save space, and because that stuff's working):
var outerRadius = w/2;
var innerRadius = 0;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var svg= d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var arcs = svg.selectAll("g.arc")
.data(pie(datamod[0]))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + outerRadius + ", " +outerRadius + ")");
arcs.append("path")
.attr("fill", function(d,i){
return colors[i];
})
.attr("d", arc);
And then to update...clickToChange() is called when users click anywhere in the body. it's loading new data from the next spot in the 2-d array and also updates text for the year, and there's some code in here to keep it from restarting if it's already running... But the main problem I think is with the code to update the arcs...
function clickToChange()
{ if(!isRunning)
{
isRunning = true;
myTimer =setInterval(function() {if (yearcounter < 11)
{
yearcounter++;
}
else
{
yearcounter = 0;
stopDisplay();
}
var thisyear = 2000 + yearcounter; //updating happens here...
svg.selectAll("g.arc")
.data(pie(datamod[yearcounter]))
.transition()
.attr("class", "arc")
.attr("transform", "translate(" + outerRadius + ", " +outerRadius + ")");
arcs.attr("fill", function(d,i){
return colors[i];
// console.log(d.value);
// return "rgb(" + colorscale(d.value) + ",50,50)";
})
.attr("d", arc);
document.getElementById('year').innerHTML = thisyear;
}, 2000); //end set interval
}//end if
}
function stopDisplay()
{
clearInterval(myTimer);
isRunning = false;
}
I think the problem is that I'm possibly not binding the data properly to the correct elements, and if I'm using the correct notation to select the arcs?
Okay, I can see multiple issues/drawbacks with your approach.
1) In your code:
arcs.append("path")
.attr("fill", function(d,i){
return colors[i];
})
.attr("d", arc);
arc is a function call that you are making that doesn't actually exist in the code that you have shared with us, or you need to write. You have this arc function call multiple times, so this will need to be addressed.
2) I would check into using the .on("click", function(d,i) { do your transitions here in this function call }); method instead of setting the transition and attributes of each of the items. I have found that it makes the transition calls easier to manage if you start doing anything more fancy with the transitions. You can see an example of what I mean in the Chord Diagram at http://bl.ocks.org/mbostock/4062006
Hopefully this helps you out a bit.
I've been trying to make a specific type of force direct graph, similar to this (http://bl.ocks.org/mbostock/950642):
However, instead of having all the same images I wish to have different images representing different information on the graph.
My first step to this is being able to change all the circle images to random linked shapes. Whatever I try to implement in my code, the circles I have just disappear, instead of being replaced by different shapes. Any help on this problem would be great. Here is the code. Sorry, I'm also new to this site.
// nodes
var nodeSelecton = svg.selectAll(".node").data(nodes).enter().append("g").attr({
class : "node"
}).call(force.drag);
nodeSelecton.append("circle").attr({
r : nodeRadius
}).style("fill", function(d) {
return color(d.group);
});
nodeSelecton.append("svg:text").attr("text-anchor", "middle").attr('dy', ".35em").text(function(d) {
return d.name;
});
// Add a new random shape.
// nodes.push({
// type: d3.svg.symbolTypes[~~(Math.random() * d3.svg.symbolTypes.length)],
// size: Math.random() * 300 + 100
This is a jsfiddle that is equivalent to the first example that you linked. I just changed getting data to be from the JavaScript code instead of json file, since jsfiddle doesn't support external json files that well.
First Solution
Now, let's replace constant image with a set of different images
Instead of this code:
.attr("xlink:href", "https://github.com/favicon.ico")
we'll insert this code:
.attr("xlink:href", function(d) {
var rnd = Math.floor(Math.random() * 64 + 1);
var imagePath =
"http://www.bigbiz.com/bigbiz/icons/ultimate/Comic/Comic"
+ rnd.toString() + ".gif";
console.log(imagePath);
return imagePath;
})
and we'll get this:
Second Solution
As you suggested in your code from the question, one could use built-in SVG symbols.
Instead of this whole segment for inserting images:
node.append("image")
.attr("xlink:href", "https://github.com/favicon.ico")
.attr("x", -8)
.attr("y", -8)
.attr("width", 16)
.attr("height", 16);
we could use this code:
node.append("path")
.attr("d", d3.svg.symbol()
.size(function(d) {
return 100;
})
.type(function(d) {
return d3.svg.symbolTypes[~~(Math.random() * d3.svg.symbolTypes.length)];
}))
.style("fill", "steelblue")
.style("stroke", "white")
.style("stroke-width", "1.5px")
.call(force.drag);
and we'll get this:
Hope this helps.