I was looking into the following example by Mike Bostock on focus + context zooming. https://bl.ocks.org/mbostock/1667367.
I was wondering if we can link multiple charts with a main graph. Something similar to the attached image. I am quiet new to d3.js so i might have missed something but i am unable to find any links on how to go about it. All of the graphs have equal data points.
Thanks!
It depends obviously on how your data is organized. I imagine you have a data array as follows:
[ {date : ... /*x-coordinate*/
price1 : .../*first y-coordinate*/
price2 : .../*second y-coordinate*/
/* ...and as many as you like*/
},
{date : ...
price1 : ...
price2 : ... }
]
You also have an array containing the names of the fields you want to fetch as y-axis:
fields = ["price1", "price2", ...]
So first thing to do is a way to extract the data for each separate curve. This can be done as follows:
function singleCurveData(fieldId) {
return data.map(function (d) {
return {date: d.date, price: d[fieldId]};
});
}
If your data is organized differently, only this function needs to change. Basically, it receives the id of the graph you want to draw, and outputs the data for this specific graph in a standard fashion.
Now to the drawing section. You need as many focus parts as different fields you want to show, each one containing a single area; and a single context part containing many area2s.
var focus = svg.selectAll(".focus")
.data(fields) //associate one field id to each focus block
.enter()
.append("g")
.attr("class", "focus")
.attr("transform", function(d,i) {return "translate(" + margin.left + "," + (margin.top - i*focusHeight) + ")"});
//the above line takes care of the positioning, you need to know the target height of a focus block.
var context= ...//as before
And now we move on to drawing the curves:
focus.append("path") //append one path per focus element
.datum(function(fieldId) {return singleCurveData(fieldId)}) //only this line changes
.attr("class", "area")
.attr("d", area);
context.selectAll("path")
.data(fields) // add a "path" for each field
.enter()
.append("path") //here the datum for the path is the field Id
.datum(function(fieldId) {return singleCurveData(fieldId)})
//now the datum is the path data for the corresponding field
.attr("class", "area")
.attr("d", area2);
This should be all there is to it. Good luck!
Related
m creating a scatter plot and I have problems plotting my circles (datapoints).
When appending the first set of circles it is drawn fine on the graph. However the next set I try to append won't be draw for some reason. How can this be? Am I using the Enter/append/select wrong the 2nd time?
I have a JSFiddle with my code: http://jsfiddle.net/4wptM/
I have uncommented the parts where I load and manipulate my data and created the same array with a smaller sample. As it can be seen only the first set of circles are shown and the 2nd ones aren't.
My code of the circle section is pasted below:
var circle = SVGbody
.selectAll("circle")
.data(graphData[0])
.enter()
.append("circle")
.attr("cx",function(d){return xScale(100);})
.attr("cy",function(d){return yScale(parseFloat(d))})
.attr("r",5);
circle = SVGbody
.selectAll("circle")
.data(graphData[1])
.enter()
.append("circle")
.attr("cx",function(d){return xScale(200);})
.attr("cy",function(d){return yScale(parseFloat(d))})
.attr("r",5);
I just have those 2 copied to try and figure out the problem. The actual code I have is in the following for loop. When I run it in this loop it draws the circles for when the index is 1 and a few of when the index is 3.
for(var i = 0;i < graphData.length;i++){
var circle = SVGbody
.selectAll("circle")
.data(graphData[i])
.enter()
.append("circle")
.attr("cx",function(d){return xScale((i*100)+100);})
.attr("cy",function(d){return yScale(parseFloat(d))})
.attr("r",20);
//console.log(i + " ::::::: " + graphData[i])
}
Some help would be so greatly appretiated. I really can't figure out what I'm doing wrong.
When operating on a existing set of elements (as it is the case here on the second .selectAll("circle") the .data() method uses only these elements from the array which have no corresponding index in the selecton made with .selectAll(). To prevent this behaviour you will have to add a key function as the second parameter of .data() as explained here and here.
Here this function only has to return each element of the array:
function (d) {
return d;
}
In the fiddle it would look something like this:
var circle = SVGbody
.selectAll("circle")
.data(graphData[0], function(d) { return d; }) // <-- this one
.enter()
.append("circle")
.attr("cx",function(d){return xScale(100);})
.attr("cy",function(d){return yScale(parseFloat(d))})
.attr("r",5);
fiddle
And to change the fill color of an element you have to use .style("fill", ...) and not .attr("fill", ...)
.style("fill", "green")
I am using d3.js to build a stacked bar graph. I am referring to this graph http://bl.ocks.org/mbostock/3886208
I want to add a small square of different color on the bars which have equal value. For example in this graph- if population of 25 to 44 Years and 45 to 64 Years is equal then i want to show a square of 10,10(width,height) on both bars related to CA. This is what I was doing but its not showing on the bar:
var equalBar = svg.selectAll(".equalBar")
.data(data)
.enter().append("g")
.attr("class", "equalBar")
.attr("transform", function(d){ return "translate(" + x(d.states) + ",0"; });
equalBar.selectAll("rect")
.data(function(d) { return d.ages;} )
.enter().append("rect")
.attr("width", 10)
.attr("y", function(d){
return y(d.y1);
})
.attr("height", function(d)
{ return 10; })
.style("fill", "green");
Thanks a lot for help.
What you're trying to do isn't really compatible with the D3 approach to data management. The idea of selections relies on the data items to be independent, whereas in your case you want to compare them explicitly.
The approach I would take to do this is to create a new data structure that contains the result of these comparisons. That is, for each population group it tells you what other groups it is equal to. You can then use this new data to create the appropriate rectangles.
I have two g elements each containing circles. Circles are organized using force.layout. The g elements are transitioning.
You can see here: demo. Reduced code:
var dots = svg.selectAll(".dots")
.data(data_groups)
.enter().append("g")
.attr("class", "dots")
.attr("id", function (d) {
return d.name;
})
...
.each(addCircles);
dots.transition()
.duration(30000)
.ease("linear")
.attr("transform", function (d, i) {
return "translate(" + (150 + i * 100) + ", " + 450 + ")";
});
function addCircles(d) {
d3.select(this).selectAll('circle')
.data(data_circles.filter(function (D) {
return D.name == d.name
}))
.enter()
.append('circle')
.attr("class", "dot")
.attr("id", function (d) {
return d.id;
})
...
.call(forcing);
}
function forcing(E) {
function move_towards(alpha) {
...
}
var force = d3.layout.force()
.nodes(E.data())
.gravity(-0.01)
.charge(-1.9)
.friction(0.9)
.on("tick", function (e) {
...
});
force.start();
}
I need to move circle (for example id=1) from the first g element to the second one using transition.
Any suggestions are appreciated.
It can be done.
What I did was:
1) Use jquery to append the point to the target group
2) Use a transformation (no transition) to move the point back to its original location
3) Transition the point to its new location
The jQuery was used for the appendTo method. It can be removed and replaced with some pure Javascript stuff, but it's quite convenient.
I've got a partially working fiddle here. The green points work right, but something is going wrong with the blue ones. Not sure why.
In my view, transitions work on a single element. If an element changes its position in the DOM tree, from below one g to another, I can't think of a way to make that as one smooth transition because it's basically a binary split: Now there's an element under one g, now it's gone but there's another one somewhere else.
What I'd do in order to achieve what I think you want to do: Group everything under the same ´g´, assign color and translation individually, then change color and translation for that single element you want to change.
But don't take that as a reliable statement that you can't do it the way you originally wanted.
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 implemented this d3 visualization http://bl.ocks.org/4745936 , to be loaded with dynamic data instead of a .tsv
in my case, once my server passes new information to the selector, a second chart gets rendered under the first one, instead of modifying the contents of the existing graph.
I believe it has to do with this append method.
var svg = d3.select(selector).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
so I tried adding other exit().remove() methods to legend and cities variables right after they append('g'); but my javascript console says the exit() method does not exist at that point.
I feel I have the completely wrong approach, how do I update an existing graph like this? Having a second and third graph get generated alongside the previous ones is not the outcome I wanted at all
You're right the append method is adding a new svg element every time. To prevent the duplicate charts you need to check if the svg element exists already. So try something like this at the begining:
var svg = d3.select("#mycontainer > svg")
if (svg.empty())
svg = d3.select(selector).append("svg");
...
As stated in the exit() docs, This method is only defined on a selection returned by the data operator. So make sure that you're calling exit on a selection returned from .data(..).
scott's answer is one way of ensuring that the initialization happens only once.
However, I prefer a more d3-ic way of handling this:
var svg = d3.select(selector)
.selectAll('svg')
.data( [ dataFromTSV ] ); // 1 element array -> 1 svg element
// This will be empty if the `svg` element already exists.
var gEnter = svg.enter()
.append('svg')
.append('g');
gEnter.append( ... ); // Other elements to be appended only once like axis
svg.attr('width', ...)
.attr('height', ...);
// Finally, working with the elements which are surely in the DOM.
var g = svg.select("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
g.selectAll(...).attr(...);
This approach is exemplified in the reusable charts example's source code.
I prefer this approach because it keeps the code very declarative and true to the visualisation by hiding away the logic of initialisation and updates.
I would modify the original example: http://jsfiddle.net/8Axn7/5/ to http://jsfiddle.net/3Ztt8/
Both the legend and the graph are defined from svgElem with one single element of data:
var svgElem = d3.select("#multiLinegraph").selectAll('svg')
.data([cities]);
// ...
var svg = svgElem.select('g');
// ...
var city = svg.selectAll(".city")
.data(
function (d) { return d; },
function (d) { return d.name; } // Object consistency
);
// ...
var legend = svg.selectAll('g.legend')
.data(
function(d) { return d; },
function (d) { return d.name; } // Object consistency
);
Also, the static properties are set only once when the element is entered (or exited), while the update properties are set (transitioned) with each update:
gEnter.append("g")
.attr("class", "y multiLineaxis")
.append('text')
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Requests (#)");
svg.select('g.y.multiLineaxis').transition().call(yAxis);
The code, in my opinion, follows the cycle of enter-update-exit cleanly.
I was able to solve this problem with some jQuery and CSS voodoo
basically since my d3 graph adds an svg element to an existing selector (a div in my case), I was able to check for the name of this dynamically
var svgtest = d3.select(selector+" > svg"); getting the svg subchild element of that div. then I could use jquery to remove that element from the dom completely, and then let d3 continue running and append svg's all it wants!
var svgtest = d3.select(selector+" > svg");
if(!svgtest.empty())
{
$(selector+" > svg").remove();
}
First of all you should remove old svg, after then you can add updated charts.
For that you should add only one line before you append svg.
And its working.
var flag=d3.select("selector svg").remove();
//----your old code would be start here-------
var svg = d3.select(selector).append("svg")