I am a noob with d3.js. I am using topoJSON data to render maps and so far it's been working great. Now I want to overlay some data such as text or circles on top of each country/region and I am hitting a wall. I have code similar to this:
var countries = g.append("g")
.attr("id", "countries")
.selectAll("path")
.data(topojson.feature(collection, collection.objects.countries).features)
.enter().append("path")
.attr("d", path)
.style("fill", colorize)
.attr("class", "country")
.on("click", clicked)
which properly renders my map. In order to overlay some circles on it, I do the following:
countries
.append("circle")
.attr("r", function(d, i, j) {
return 10; // for now
})
// getCentroid below is a function that returns the
// center of the poligon/path bounding box
.attr("cy", function(d, i, j) { return getCentroid(countries[0][j])[0]})
.attr("cx", function(d, i, j) { return getCentroid(countries[0][j])[1]})
.style("fill", "red")
Which is pretty cumbersome (specially the way it accesses the countries array), but it succeeds at appending a circle for each path representing a country. The problem is that the circle exists in the SVG markup, but doesn't show up at all in the document. I am obviously doing something wrong, but I am at a loss of what is it.
The problem is that you're appending the circle elements to path elements, which you can't do in SVG. You need to append them to the parent g elements. The code would look something like this.
var countries = g.selectAll("g.countries")
.data(topojson.feature(collection, collection.objects.countries).features)
.enter().append("g")
.attr("id", "countries");
countries.append("path")
.datum(function(d) { return d; })
.attr("d", path)
// etc
countries.append("circles")
// etc
Related
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. For the most part, my code works, but for some reason, the j index in the anonymous function for the fill returns an array of repeated circle instead of returning the parent of the current element. I believe this may have something to do with the way I created the svg and selected the elements, but I can't figure it out. Below is an excerpt of my code that shows how I created the svg, the line path and the circles.
var svgb = d3.select("body")
.append("svg")
.attr("id","svg-b")
.attr("width", width)
.attr("height", height)
var gameb = svgb.selectAll(".gameb")
.data(games)
.enter()
.append("g")
.attr("class", "gameb");
gameb.append("path")
.attr("class", "line")
.attr("d", function(d) {return line_count(d.values); })
.style("stroke", function(d) { return color(d.name); })
.style("fill", "none");
gameb.selectAll("circle")
.data(function(d) {return d.values;})
.enter()
.append("circle")
.attr("cx", function(d) {return x(d.date);})
.attr("cy", function(d) {return y_count(d.count);})
.attr("r", 3)
.style("fill", function(d,i,j) {console.log(j)
return color(games[j].name);});
j (or more accurately, the third parameter) will always be the nodes in the selection (the array of circles here), not the parent. If you want the parent datum you can use:
.attr("fill", function() {
let parent = this.parentNode;
let datum = d3.select(parent).datum();
return color(datum.name);
})
Note that using ()=> instead of function() will change the this context and the above will not work.
However, rather than coloring each circle independently, you could use a or the parent g to color the circles too:
gameb.append("g")
.style("fill", function(d) { return color(d.name); })
.selectAll("circle")
.data(function(d) {return d.values;})
.enter()
.append("circle")
.attr("cx", function(d) {return x(d.date);})
.attr("cy", function(d) {return y_count(d.count);})
.attr("r", 3);
Here we add an intermediate g (though we could use the original parent with a few additional modifications), apply a fill color to it, and then the parent g will color the children circles for us. The datum is passed on to this new g behind the scenes.
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.
I am trying to set up a force directed layout in d3 and have my nodes start with an initial radius at 0. I then want for the user to be able to press a button and have the radius of the nodes scale to a size in accordance with a json data value. When I try to do this however, I get a javascript error "Cannot read property 'FIELD4' of undefined.
Here is the json data: https://api.myjson.com/bins/2n7do
And here is the code:
// Update nodes.
circles = circles.data(data);
circles.exit().remove();
var nodeEnter = circles.enter().append("g")
.attr("class", "node")
.style("fill", function(d) { return color(d.FIELD5); })
.style("opacity", 0.75)
.call(force.drag);
nodeEnter.append("circle")
.attr("r", 9)
d3.select(circles).transition()
.delay(3000)
.duration(1000)
.attr("r", function(d) { return d.FIELD4 * 0.000195 });;
circles is d3 selection. By doing d3.select(circles) you select selection. I don't think it's valid.
Instead of d3.select(circles).transition() try circles.transition()
I'm working on a d3.js pie chart application. I am trying to develop the functionality that when you click on the legend rectangles, it toggles the slice on/off as well as the fill inside the legend rectangle.
http://jsfiddle.net/Qh9X5/3136/
legend
Rects
.enter()
.append("rect")
.attr("x", w - 65)
.attr("y", function(d, i){ return i * 20;})
.attr("width", 10)
.attr("height", 10)
.style("fill", function(d, i) {
return methods.color(i);
})
.style("stroke", function(d, i) {
return methods.color(i);
})
.on('click', function(d, i){
onLegendClick(d, i);
})
Here's one way to solve your problem:
One change required in your code is to use key functions, so that d3 matches the filtered data to the corresponding DOM node. Labels seem to be a proper key in your dataset.
Simply use:
.data(this.piedata, function(d) { return d.data.label});
instead of
.data(this.piedata);
Then, in your OnLegendClick function, you want to select all the legend's rect and all the svg arcs matching with the clicked element.
Workflow is :
select the DOM elements
match with the selected data
apply changes
Here's how to do it:
function onLegendClick(dt){
d3.selectAll('rect').data([dt], function(d) { return d.data.label}).style("opacity", function(d) {return Math.abs(1-d3.select(this).style("opacity"))})
d3.selectAll('.pie').data([dt], function(d) { return d.data.label}).style("opacity", function(d) {return Math.abs(1-d3.select(this).style("opacity"))})
}
I let you adjust the "toggle" feature. You might also want to change the texts in addition to the arcs, for this use another selection.
Updated jsfiddle: http://jsfiddle.net/Qh9X5/3138/
I'm trying to edit the data of created circles in D3. Below my code is pasted of me creating a lot of circles based on some data from graphData.
Supposed I'd want to re-arrange my circles Y position with a new dataset, by transitioning them to their new destinations. How would perform this task? I've tried using attr.("cy", function(d){return yScale(parseFloat(d))} ) to update my Y-coordinates by adding data(graphData[i], function(d){return d;}) with my new data, but this does not work.
You can take a look at my JSFiddle: http://jsfiddle.net/RBr8h/1/
Instead of the for-loop in the following code I've created circles on 2 ticks of my X-axis. I have 3 sets of data and I've used to of them in the example in the fiddle. I'd like to able to use the 3rd dataset instead of the 2 first ones on both circles.
var circle;
for(var i = 0;i < graphData.length;i++){
circle = SVGbody
.selectAll("circle")
.data(graphData[i], function(d){return d;})
.enter()
.append("circle")
.attr("cx",xScale(0))
.attr("cy", yScale(minAxisY))
.attr("r",4)
.style('opacity', 0)
.transition()
.duration(1000)
.attr("cx", function(d){
return spreadCircles(i);
})
//.attr("cy", function (d, i){ return yScale(i); })
.style('opacity', 1)
.transition()
.duration(1500)
.attr("cy", function(d){return yScale(parseFloat(d))} );
Thank you for your help in advance!
To put some flesh on Lars comment, here is a FIDDLE leveraging the enter/update/exit pattern to help you out. I have altered and simplified your code (and data) just enough to demonstrate the principle.
function updateCircles(dataset,color) {
var circle = SVGbody
.selectAll("circle")
.data(dataset, function(d) { return d; });
circle
.exit()
.transition().duration(750)
.attr("r", 0)
.remove();
circle
.enter()
.append("circle");
circle
.attr("cx",function(d){return xScale(100);})
.attr("cy",function(d){return yScale(parseFloat(d))})
.attr("r",0)
.transition().duration(1500)
.attr("r",5)
.style("fill", color);
};
Update fiddle with data keyed off by index...so, circles just have their position updated.