Setting different images for D3 force-directed layout nodes - javascript

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.

Related

Redrawing a key on top of a D3 projection after transition

I'm working with a D3 map projection similar to Mike Bostock's Choropleth seen here.
The issue I'm having is that I've added a transition; and when I transition the projection, the map key (seen in the top right corner) is being covered by the background color of the map.
I know I probably just need to redraw the g layer after the transition, but I'm not able to get that working as expected.
I'm originally drawing the key on the map with the following code:
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(0,40)");
g.selectAll("rect")
.data(color.range().map(function(d) {
d = color.invertExtent(d);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().append("rect")
.attr("height", 8)
.attr("x", function(d, i) { return 350 + (i * 30)})
.attr("width", 30)
.attr("fill", function(d) { console.log(d[1]); return color(d[1]); });
g.append("text")
.attr("class", "caption")
.attr("x", x.range()[0])
.attr("y", -6)
.attr("fill", "#000")
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("Number of Licensed Establishments");
g.call(d3.axisBottom(x)
.tickSize(13)
.tickValues(color.domain()))
.select(".domain")
.remove();
Then I'm transitioning the projection with this code (which also works fine).
path = d3.geoPath(projection);
svg.selectAll("path").transition().duration(2000).attr("d", path);
But the key gets covered. I've tried redrawing it like this:
g.selectAll("g").attr("transform", "translate(0,40)");
It doesn't do anything though. What step am I missing to correctly redraw that g layer on top?
Transitioning a path shouldn't change where it appears in the DOM. Transitioning element attributes with d3 modifies that element in place in the DOM. The following example should demonstrate this (path is appended first and should be behind the text, the path then transitions its d attribute through two d3 symbol paths remaining behind the text):
var svg = d3.select('body').append('svg').attr('width',400).attr('height',200);
var cross = "M-21.213203435596427,-7.0710678118654755L-7.0710678118654755,-7.0710678118654755L-7.0710678118654755,-21.213203435596427L7.0710678118654755,-21.213203435596427L7.0710678118654755,-7.0710678118654755L21.213203435596427,-7.0710678118654755L21.213203435596427,7.0710678118654755L7.0710678118654755,7.0710678118654755L7.0710678118654755,21.213203435596427L-7.0710678118654755,21.213203435596427L-7.0710678118654755,7.0710678118654755L-21.213203435596427,7.0710678118654755Z";
var star = "M0,-29.846492114305246L6.700954981042517,-9.223073285798176L28.38570081386192,-9.223073285798177L10.8423729164097,3.5229005144437298L17.543327897452222,24.146319342950797L1.7763568394002505e-15,11.400345542708891L-17.543327897452215,24.1463193429508L-10.842372916409698,3.522900514443731L-28.38570081386192,-9.22307328579817L-6.7009549810425195,-9.223073285798176Z";
var wye = "M8.533600336205877,4.926876451265144L8.533600336205877,21.9940771236769L-8.533600336205877,21.9940771236769L-8.533600336205877,4.9268764512651435L-23.31422969000131,-3.6067238849407337L-14.78062935379543,-18.387353238736164L0,-9.853752902530289L14.78062935379543,-18.387353238736164L23.31422969000131,-3.6067238849407337Z"
var symbol = svg.append('path')
.attr('transform','translate(100,100)')
.attr('d', cross )
.attr("fill","orange");
var text = svg.append('text')
.attr('x', 100)
.attr('y', 105)
.style('text-anchor','middle')
.text('THIS IS SOME TEXT')
symbol.transition()
.delay(2000)
.attr('d', star )
.duration(2000)
.transition()
.attr('d', wye )
.duration(2000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
Given your example, it is likely that the key is initially rendered behind the features of the map - only there is no overlap between the two. Each appears as intended. When transitioning, with say a zoom, the features overlap and the key is hidden. As noted in the comments, try g.raise() or d3.select(".key").raise() to move the key to the bottom of the parent container, effectively lifting it above other svg elements (as elements are rendered in the order they appear in the DOM, as close as we get to a z-index in svg). You should only need to apply .raise() once - as the transition won't change the ordering, or alternatively, ensure that the key is appended to the svg last.

How to dynamically append text to svg using d3 and Ajax?

I'm clueless on Ajax calls, have been reading on them for a few hours, but all of the tutorials mention load method and a listener like click.
I have a function (drawThreat) that adds some icons (fontawesome) on my svg, there is a json file with a bunch of x and ys, all I need to do is to have an ajax call that runs this function with all of the x and ys in the json file every 5 seconds and updates the svg element on the page. Here is the function:
function drawThreat (x, y){
var canvas = d3.select("#map")
.append("svg")
.attr("width", 500)
.attr("height", 500)
.attr("id", "Threat");
var Threat = canvas.append('svg')
.append('text')
.attr('text-anchor', 'middle')
.attr('dominant-baseline', 'central')
.attr("x", x)
.attr("y", y)
.attr("class", "threat")
.style('font-family','FontAwesome')
.style('font-size','20px')
.style('fill', 'red')
.text(function (d) {
return '\uf2be'
});
return Threat
};
Any help would be appreciated:) even if it is a link to a tutorial you find related to the question. I looked at 6 or 7 tutorials so far with no luck.
You basically can have a code similar to the below one if I understood your need correctly :
var dataFileUrl = "url-to-your.json"; // assign the url to a variable
var canvas = d3.select("#map") // get a ref from the SVG element
.append("svg") // you might want to define it only one time
.attr("width", 500)
.attr("height", 500)
.attr("id", "Threat");
var updateInterval = setInterval(function(){
d3.json(dataFileUrl , function (jsonData) { // AJAX call
drawThreat(jsonData); // calls main function
});
},5000); // every 5 * 1000ms
function drawThreat (jsonData){
canvas.selectAll('text.threat').remove(); // makes sure we don't have old icons
canvas.selectAll('text')
.data(jsonData) // for each set in json
.enter()
.append('text') // create a text and append it to svg canvas
.attr("class", "threat") // with class of threat
.attr("x", function (d) { return d[0]; }) // first element of each set
.attr("y", function (d) { return d[1]; }) // second element of each set
.text('\uf2be');
};
to reduce js codes I suggest adding styles and attributes using CSS:
.threat{
text-anchor:middle;
dominant-baseline:central;
font-family:FontAwesome;
font-size:20px;
fill:red;
}
You can also see it in action here : https://codepen.io/FaridNaderi/pen/awPBwm
Hope it helps you to get the point.

D3 Diagram : how may i assign images inside a node

you can find something like below in the jsFiddle demo included in this question, and i am wondering how may I assign images into each node.
var graph = {
"nodes":[
{"name":"1","rating":90,"id":2951},
]
}
I have jsFiddle Demo in this link : http://jsfiddle.net/JSDavi/qvco2Ljy/
Update 1 :
node.append("circle")
.attr("r", function(d) { return d.weight * 2+ 12; })
.style("fill", function(d) { return color(1/d.rating); });
node.append("image")
.attr("xlink:href", d=> d.url)
//people icon's location (x,y)
.attr("x", function(d) { return d.weight * 2+ 12; })
.attr("y", function(d) { return d.height * 2+ 12; })
//people icon's size
.attr("width", width/10)
.attr("height", height/10);
The codes above is how I set the circle and images
but they never stick together.
this is my updated demo : http://jsfiddle.net/qvco2Ljy/116/
For each object, set the URL of the image:
{name: "1", rating: 90, id: 2951, url: "someUrl"},
Then, instead of appending circles, append an image
node.append("image")
.attr("xlink:href", d=> d.url)
.attr("x", -width/2)
.attr("y", -height/2)
.attr("width", width)
.attr("height", height);
Where width and height are the corresponding image width and height.
PS: have in mind that I'm simply answering your question ("how may I assign images into each node?"). If giving up the circles is not an option for you, you'll have to use a pattern.

Wordcloud update data/ working example of adding words to cloud?

I am still pretty new to d3.js and I am diving into a wordcloud example using the
d3-cloud repo : https://github.com/jasondavies/d3-cloud
The example which is in there works for me, I turned it into a function so I can call it when data updates:
wordCloud : function(parameters,elementid){
var p = JSON.parse(JSON.stringify(parameters));
var fill = d3.scale.category20();
if (d3.select(elementid).selectAll("svg")[0][0] == undefined){
var svg = d3.select(elementid).append("svg")
.attr("width", 500)
.attr("height", 500)
.append("g")
.attr("transform", "translate(300,300)");
}else var svg = d3.select(elementid).selectAll("svg")
.attr("width", 500)
.attr("height", 500)
.select("g")
.attr("transform", "translate(300,300)");
d3.layout.cloud().size([300, 300])
.words(p.data)
.padding(5)
.rotate(function(d) {return ~~(Math.random()) * p.cloud.maxrotation; })
.font("Impact")
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
function draw(words) {
console.log(words)
console.log(words.length)
svg.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) {return d.size + "px"; })
.style("font-family", "Impact")
.style("fill", function(d, i) { return fill(i); })
.attr("text-anchor", "middle")
.text(function(d) {console.log("enter text " + d.text) ; return d.text; });
svg.selectAll("text")
.data(words).transition().duration(2000).attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + Math.random() * p.cloud.maxrotation + ")";
})
}
}
The code works for me.
element id = the elements you bind to
parameters = all parameters which i should be able to set, including data (parameters.data).
Except for the packaging the code wasn't altered much from the original:
https://github.com/jasondavies/d3-cloud/blob/master/examples/simple.html
However when I add a new word to the wordcloud (so when I update the data), the new word is not recognized. I have put log output on several places and apparently in the draw function the data is incorrect but before it is ok.
for example:
original: [{"text":"this","size":5},{"text":"is","size":10},{"text":"a","size":50},{"text":"sentence","size":15}]
(the code adds other properties but this is for simplicity of explanation)
I add: "testing" with a size of 5
correct would be
[{"text":"this","size":5},{"text":"is","size":10},{"text":"a","size":50},{"text":"sentence","size":15},{"text":"testing","size":5}]
but I get results like:
[{"text":"a","size":50},{"text":"testing","size":5},{"text":"this","size":5},{"text":"sentence","size":15}]
--> new word added , an older one removed (don't know why) and array was mixed up.
QUESTION:
Anybody have an idea what I am doing wrong?
or
Does anybody have a working example of a d3.js wordcloud which you can update with new words by means of lets say an input box?
I think u got the same problem with me. The size of all the words do not fit in your svg and d3.layout.cloud somehow remove the oversized word. Try to increase the width and height of your svg or decrease the size of your word. What I done is check whether the x,y,width and height of the word is it out of the box. If yes, decrease the size or increase the width and height. Correct me if i am wrong

Animating histogram with D3

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

Categories

Resources