I know there are many questions here about how to globalize the scope of variables that have been updated inside a json callback function. And I have been trying to work off those examples for days now but I cant seem to work out how I can adapt that to my code when my json callbacks are on an event eg.on right click(context menu). I have been trying to use this example but have not been successful to try and adapt it to my code:
function myFunc(data) {
console.log(data);
}
d3.json('file.json', function (data) {
var json = data;
myFunc(json);
}
I am working with a scatterplot in d3. My first connection just adds two rows of my table into both of the arrays. Each row represents a dot. When I click on one of these dots, a connection is made to the database and links to that selected dot appear on the graph as other dots. And these are added to the baseData array and the libraryData remains the same. WHen I right click on one of these dots that dot is added to the libraryData array.But as indicated in the code, instances of libraryData outside of the function has not been updated. Below is my code
var libraryData = [];
var baseData = [];
d3.json("connection4.php", function(error,dataJson) {
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = +d.counter;
libraryData.push(d);
baseData.push(d);
})
var circles = svg.selectAll("circle")
.data(libraryData) // libraryData here remains unchanged even after librayData has been updated in the function below!
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill","blue")
.on("click", clickHandler)
function clickHandler (d, i) {
d3.json("connection2.php?paperID="+d.ID, function(error, dataJson) {
dataJson.forEach(function(d) {
d.YEAR = +d.YEAR;
d.counter = +d.counter;
baseData.push(d);
})
var circles = svg.selectAll("circle")
.data(baseData)
.enter()
.append("circle")
.attr("class", "dot")
.attr("r", 3.5)
.attr("cx", function(d) {return x(YearFn(d))})
.attr("cy", function(d) {return y(Num_citationsFn(d))})
.style("fill", "red")
.on("contextmenu", rightClickHandler);
})
function rightClickHandler (d, i) {
d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) {
})
d3.select(this)
.style("fill", "blue");
libraryData.push(d);
console.log(libraryData);// updated
}
console.log(libraryData)// not updated
});
I am new to d3 and I would appreciate any help and feedback thanks in advance!!
It's not scope, it's a timing issue
function rightClickHandler (d, i) {
d3.json("connection6.php?paperID="+d.ID, function(error, dataJson) {
})
d3.select(this)
.style("fill", "blue");
libraryData.push(d);
console.log("I bet I'm second", libraryData);// updated
}
console.log("I bet I'm first", libraryData)// not updated
});
thefunction(error, dataJson) in the json call only executes once json is returned from your php function which can take a while. Meanwhile, your program performs the second call to console.log runs straight away and before the function in the json call has added anything to libraryData.
Run the above with the changes to console.log to see
Basically anything you want to do that depends on library data being updated must be called inside function(error, dataJson)
Related
Why does the following work:
var line = d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; });
var path = d3.select("#frame")
.append("path")
.attr("class", "line")
.attr("d", line(nodes.data()))
But if I directly integrate the function without declaring it first like this it doesn't work (It doesn't draw the line). Why is that? What do I have to change for it to work?
var path = d3.select("#frame")
.append("path")
.attr("class", "line")
.attr(
"d",
function() {
d3.line()
.x(function() { return nodes.data().x })
.y(function() { return nodes.data().y });
}
);
The code
var line = d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; });
is creating a line generator. A line generator is a function. If you call this function and pass it your data array, then it returns the a string for the "d" attribute of an SVG path, which defines the shape of the line.
The line generator needs to know how to get the x and y coordinates for a given element in your data array. This is defined by the functions that you pass to line.x() and line.y(). These functions get called individually for each element in your data array.
In your code, function(d) { return d.x; } and function(d) { return d.y; } will be called on each element in the data array in order to get the x and y coordinates for that element. The argument to these functions, d, is a single element from your data array. It is not the entire data array.
If you don't want to define the line generator in a separate variable, then you could do the following:
var path = d3.select("#frame")
.append("path")
.attr("class", "line")
.attr("d", d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })(nodes.data())
);
This replaces line in your first block of code with the entire line generator.
Your code doesn't work for two reasons. First, your line generator is
d3.line()
.x(function() { return nodes.data().x })
.y(function() { return nodes.data().y })
The functions that you are passing to x() and y() do not work correctly. These functions should define how to get the x and y coordinates for a single element in your data array, like function(d) { return d.x; }. The argument, d, is one element from your data array.
Second, in the code that you have, the line generator is never called on your data array. You don't need to put the line generator inside of another function, but if you did then it would look like this:
function() {
return d3.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })(nodes.data());
}
But there's no need for this outer function. You can just do what I showed above.
I am a beginner in D3 and JavaScript development, i have succeed to generate a multi-line graph ( generated with an JS object) with interactivity. Every control work except that zoom alter line form.
I have tried to change data quantity and i don't know which part is guilty of that behavior. It appears after a given time, the line doesn't change and stay the same.
These pictures show this latter effect :
capture with the right line:
capture with altered line:
If anyone have any idea for resolve that.
[edit] i make another pass on my code and the problem seems linked to path update. i add these blocks of code if anyone see something wrong.
function line_gen(num){
graph['lineFunction'+num] = d3.line()
.defined(function(d) {return !isNaN(d[graph.dict[num]]) })
.x(function(d) { return graph.xScaleTemp(d[graph.dict[0]]);})
.y(function(d) { return graph.yScaleTemp(d[(graph.dict[num])])})
.curve(d3.curveMonotoneX);
}
function updateData() {
var t;
function data_join(num){
if(!(graph.oldFdata.length)){
graph.dataGroup.select(".data-line"+graph.opt.name+num)
.transition()
// .duration(graph.spd_transition!=-1?graph.spd_transition:0)
.attr("d", graph['lineFunction'+num]((graph.Fdata)));
}else{
let update = graph.dataGroup.select(".data-line"+graph.opt.name+num)
.data(graph.Fdata);
update.enter()
.append("path")
.attr("d",graph['lineFunction'+num]);
update.exit().remove();
// graph.dataGroup.select(".data-line"+graph.opt.name+num)
// .transition()
// .duration(graph.spd_transition!=-1?graph.spd_transition:0)
// .attrTween('d',function(d){
// var previous =d3.select(this).attr('d');
// var current =graph['lineFunction'+num]((graph.Fdata));
// return d3.interpolatePath(previous, current);
// });
}
}
for (var i = 1; i < graph["keys_list"].length; i++) {
if(graph[("lineFunction" + i)]==null){
indic_gen(i);
indicGrp(i);
}
data_join(i);
}
for (var i = 1; i < (Object.keys(graph.Fdata[0]).length); i++) {
/* update_tooltip(i); */
set_tooltip(i);
}
}
I have resolved my problem by rerendering it once more. Not the best solution but it's works.
I have the following backbone model with a d3.drag functionality. I cannot call the model's this inside the d3's context.
I came across with solutions for similar questions by defining a variable model=this and calling by model.draw.. but how can I add it inside d3's drag?
DataMapper.Models.Anchor = Backbone.Model.extend({
defaults: {
//...
},
initialize : function(){
d3.select("#anchor").call(this.dragAnchor); //make the #anchor draggable
},
dragAnchor: d3.drag()
.on("start", function (d) {
console.log("something"); //it prints
var thisDragY = this.drawSomething(a,b,c);
// this.drawSomething is not a function
// because inside d3.drag(), 'this' refers to #anchor
// what I want to refer is the model
})
.on("drag", function (d) {})
.on("end", function (d) {}),
drawSomething: function (parent, cx, cy) {
//code
}
});
Is there a way to use underscore's bind to achieve my desired goal? Link to a useful article.
The solution was found by a team member - to call the drag as a function.
DataMapper.Models.Anchor = Backbone.Model.extend({
defaults: {
//...
},
initialize : function(){
d3.select("#anchor").call(this.dragAnchor()); //make the #anchor draggable
},
dragAnchor: function(){
var self=this;
return d3.drag()
.on("start", function (d) {
console.log("something"); //it prints
var thisDragY = self.drawSomething(a,b,c);
})
.on("drag", function (d) {})
.on("end", function (d) {}),
drawSomething: function (parent, cx, cy) {
//code
}
});
I have a somewhat nested JSON file:
{
"name": "1370",
"children": [
{
"name": "Position X",
"value": -1
},
{...}
]
"matches": [
{
"certainty": 100,
"match": {
"name": "1370",
"children": [
{
"name": "Position X",
"value": -1
},
{...}
]
}
}
]
}
I want to display it using a modified Collapsible Tree. I want to display the "match" and "certainty" when hovering the corresponding node. I've used the simple tooltip example for this.
Now I have something like this:
var nodeEnter = node.enter().append("g")
...
.on("mouseover", function(d) {
if (d.matches) {
return tooltip.style("visibility", "visible")
.text( function(d) { return d.name; } );
}
} )
...
;
I'm just using d.name for testing. I want to write a more complex function later. But that doesn't work at all. I get a tooltip, but it's empty (or contains the default value). The point which I don't understand is, that the following works:
if (d.matches) {
return tooltip.style("visibility", "visible")
.text( d.name );
}
Therefore it seems to me, that a function doesn't work at this point. What am I doing wrong?
The mistake you are making is that in your call to jQuery's .text() method, you are passing in a function, but what you want to pass in is the return value of that function. In order to do this, you simply need to invoke the function you are passing in with the argument it expects:
var nodeEnter = node.enter().append("g")
...
.on("mouseover", function(d) {
if (d.matches) {
return tooltip.style("visibility", "visible")
.text( function(d) { return d.name; }(d) );
}
} )
...
;
notice how the function is invoked using (d) after it is declared
The tooltip in the linked example does not have any data associated with it. Hence, if you try to use the text function with an accessor, it cannot get any data.
My guess is that you do not want to take data from the tooltip, but instead work with the data passed by D3 to your mouseover event:
var nodeEnter = node.enter().append("g")
...
.on("mouseover", function(d) { // <-- This is the data passed by D3, associated to your node.
if (d.matches) {
var newName = computeNameFromData(d);
return tooltip.style("visibility", "visible")
.text( newName ); // <-- Just pass a string here.
}
} )
...
;
I am trying to make a bubble chart, in that if i click on a bubble, the title of the bubble should appear in the console. I tried some ways, but was not successful.
d3.json("deaths.json",
function (jsondata) {
var deaths = jsondata.map(function(d) { return d.deaths; });
var infections = jsondata.map(function(d) { return d.infections; });
var country = jsondata.map(function(d) { return d.country; });
var death_rate = jsondata.map(function(d) { return d.death_rate; });
console.log(deaths);
console.log(death_rate);
console.log(infections);
console.log(country);
console.log(date);
//Making chart
for (var i=0;i<11;i++)
{
var f;
var countryname=new Array();
var dot = new Array();
dot = svg.append("g").append("circle").attr("class", "dot").attr("id",i)
.style("fill", function(d) { return colorScale(death_rate[i]); }).call(position);
//adding mouse listeners....
dot.on("click", click());
function click()
{
/***********************/
console.log(country); //i need the title of the circle to be printed
/*******************/
}
function position(dot)
{
dot .attr("cx", function(d) { return xScale(deaths[i]); })
.attr("cy", function(d) { return yScale(death_rate[i]); })
.attr("r", function(d) { return radiusScale(infections[i]); });
dot.append("title").text(country[i]);
}
}
});
I need the title of circle to be printed
Please help!!!
You had the good idea by using the on("click", ...) function. However I see two things:
The first problem is that you don't call the function on the click event but its value. So, you write dot.on("click", click()); instead of dot.on("click", click);. To understand the difference, let's imagine that the function click needs one argument, which would for example represent the interesting dot, what would it be? Well, you would write the following:
dot.on("click", function(d){click(d)})
Which is equivalent (and less prone to errors) to writing:
dot.on("click", click)
Now, the second point is that, indeed you want to pass the node as an argument of the function click. Fortunately, with the on event, as I used in my example, the function click is called with the argument d which represents the data of dot. Thus you can now write:
dot.on("click", click);
function click(d)
{
console.log(d.title); //considering dot has a title attribute
}
Note: you can also use another argument by writing function click(d,i) with i representing the index in the array, see the documentation for more details.
If you have a title on your data,
dot.on('click' , function(d){ console.log(d.title); });