Very much D3 newbie here, feeling my way around adapting an existing radar chart built in D3 v3.5.9
I'm having an issue in interpolating between points when there are zero values between them.
Example:
radar when all data points are present, looks fine
radar when there are zero values
The behaviour I want is for the interpolation to go around the circle, rather than just closing the sections bounded by the non-zero values.
green lines show desired behaviour whenever a zero is encountered
I have used the 'defined' function to find zero values in the source data, but I need to add something else to instruct D3 to draw the connecting lines between the desired points. Something with the index value for d, probably?
Or perhaps 'defined' is not the right function in this case?
var radarLine = d3.svg.line
.radial()
.defined(function (d) {
return d.value !== 0;
})
.interpolate("linear-closed")
.radius(function (d) {
return rScale(d.value);
})
.angle(function (d, i) {
return i * angleSlice;
});
if (cfg.roundStrokes) {
radarLine.interpolate("cardinal-closed");
}
//Create a wrapper for the blobs
var blobWrapper = g
.selectAll(".radarWrapper")
.data(data)
.enter()
.append("g")
.attr("class", "radarWrapper");
//Append the backgrounds
blobWrapper
.append("path")
//.attr("class", "radarArea")
.attr("class", function (d) {
return "radarArea" + " " + d[0].radar_area.replace(/\s+/g, "");
})
.attr("d", function (d, i) {
return radarLine(d);
})
.style("fill", function (d, i) {
return cfg.color(i);
})
.style("fill-opacity", 0);
//Create the outlines
blobWrapper
.append("path")
.attr("class", "radarStroke")
.attr("d", function (d, i) {
return radarLine(d);
})
.style("stroke-width", cfg.strokeWidth + "px")
.style("stroke", function (d, i) {
return cfg.color(i);
})
.style("fill", "none");
Any help would be greatly appreciated!
Related
I was trying to add labels to circles that are constantly moving in D3. One of the ways I found was to insert the label and the circle to a g tag. However, this causes errors whenever I want to EXIT the elements and merge them (which is not happening right now).
Is there any other way to do it? My graph right now seems to be with lower frames per second because it is not using the merge to update from the current x/y position to the new one.
The code is as follow:
var t = d3.transition()
.duration(0);
// JOIN new data with old elements.
var circles = g.append("g").selectAll('g')
.data(data.values)
.enter()
.append('g')
// EXIT elements
d3.selectAll("circle").transition()
.attr("class", "exit")
.remove();
// EXIT elements
d3.selectAll(".label")
.attr("class", "exit")
.remove();
// ENTER new elements present in new data.
// Circles
circles.append("circle")
.attr("class", "enter")
.attr("fill", function (d) { return color(d.country); })
.attr("cy", function (d) { return y(d.active_cases); })
.attr("cx", function (d) { return x(d.total_deaths) })
.merge(circles)
.transition(t)
.attr("r", 15)
// Labels
circles.append("text")
.attr("class", "label")
.attr("font-size", 10)
.style("text-anchor", "middle")
.style("fill", "white")
.attr("x", function (d) { return x(d.total_deaths) })
.attr("y", function (d) { return 3 + y(d.active_cases) })
.merge(circles)
.text(function (d) { return d.country })
I am working with d3.js and need some help regarding data usage.
I have a data array that I bind with d3 and render elements in my plot.
However, each plot item has multiple section, like, starting dot, line and ending dot, something like as below:
O-----------O O---------O
O----------O
Now currently, I am binding the data multiple times for each of the items, the steps are,
Bind data array
Render all starting dots
Bind data array
Render all Line dots
Bind data array
Render all ending dots
the problem in this method is order of rendering. if one plot item rendered over another plot item, the ending dot of the first item will be rendering over the line of 2nd plot item. Another issue is if I want to manipulate a plot item, it is problematic to trace all bits and pieces of a single plot item as they are not related in the plot grammatically.
Now my question is is there any way to bind the data once and render all elements (start dot, line and end dot) together? so that the order of rendering is correct? (in this case all elements of 2nd plot item will render over the 1st plot item).
var lineSelection = PlotGroup.selectAll(".Line")
.data(EventList);
lineSelection .enter()
.append("line")
.attr("class", "Line gline")
.attr("x1", function (d) {
return XScale(d.startTime);
})
.attr("y1", (_Position))
.attr("x2", function (d) {
return XScale(d.endTime);
})
.attr("y2", (_Position));
var RectInSelection = PlotGroup.selectAll(".RectIn")
.data(EventList);
RectInSelection.enter()
.append("rect")
.attr("class", "RectIn")
.attr("x", function (d) {
return XScale(d.startTime);
})
.attr("y", function (d) {
return _Position;
})
.attr("width", 16)
.attr("height", 16);
var RectOutSelection = PlotGroup.selectAll(".RectOut")
.data(EventList);
RectOutSelection.enter()
.append("rect")
.attr("class", "RectOut")
.attr("x", function (d) {
return XScale(d.endTime);
})
.attr("y", function (d) {
return _Position;
})
.attr("width", 16)
.attr("height", 16);
I would have made as many groups as data, and to each group i would have made the line and rectangles. This will fix the overlapping issue and multiple data binding issue.
var groups = PlotGroup.selectAll(".mygroup")
.data(EventList)
.enter()
.append("g")
.classed("mygroup", true);
//make line in the group
groups.append("line")
.attr("class", "Line gline")
.attr("x1", function (d) {
return XScale(d.startTime);
})
.attr("y1", (_Position))
.attr("x2", function (d) {
return XScale(d.endTime);
})
.attr("y2", (_Position))
//make in rectangle
groups.append("rect")
.attr("class", "RectIn")
.attr("x", function (d) {
return XScale(d.startTime);
})
.attr("y", function (d) {
return _Position;
})
.attr("width", 16)
.attr("height", 16);
//make out rectangle
groups.append("rect")
.attr("class", "RectOut")
.attr("x", function (d) {
return XScale(d.endTime);
})
.attr("y", function (d) {
return _Position;
})
.attr("width", 16)
.attr("height", 16)
Hope this helps!
My d3 multi bar does not refresh after data changes. If there is more bars it add it in the end of old but does not remove old ones. If there is less bars it does not add it at all. Axis changes all the time for that from new data
var bars = svg.select(".chart-group")
.selectAll(".state")
.data(data);
bars.enter().append("g")
.attr("class", "state")
.attr("transform", function (d) {
return "translate(" + x0Scale(d[KEY]) + ",0)";
});
bars.exit().remove();
bars.selectAll("rect")
.data(function (d) {
return d.ages;
})
.enter().append("rect")
.attr("width", x1Scale.rangeBand())
.attr("x", function (d) {
return x1Scale(d[SEGMENT]);
})
.attr("y", function (d) {
return yScale(d[DATA]);
})
.attr("height", function (d) {
return chartH - yScale(d[DATA]);
})
.style("fill", function (d) {
return color(d[SEGMENT]);
});
Edit:
Here is fiddle with my problem https://jsfiddle.net/wxw5zdws/
I achieve my goal when whole container is removed:
if (container) {
container.remove();
}
I think it is bad practice, there is an issue in my drawing bars method. It should use old elements and remove/add usseless/needed elements.
What is wrong with this bars?
The effect I'm going for in a map based visualisation is:
Red circles on a map represent data (things at locations)
When something happens at a location, we briefly (2 seconds) show another, blue circle fading out over the top.
I'm trying to work out how to do this in the D3 paradigm. Specifically: how do you represent the same thing twice?
The problem I run into is that when I try to add the same dataset twice to a given SVG canvas group, nothing gets added. That is, using code like this:
g = svg.append("g");
var feature = g.selectAll("circle")
.data(stations)
.enter().append("circle")
.style("stroke", "black")
.style("opacity", .6)
.style("fill", "red")
.attr("r", function(d, i) { return d.free_bikes; });
var emphasis = g.selectAll("circle")
.data(stations)
.enter().append("circle")
.style("stroke", "black")
.style("opacity", .6)
.style("fill", "blue")
.attr("r", function(d, i) { return d.free_bikes; });
This workaround is ok, but kludgy and potentially limiting:
g2 = svg.append("g");
var emphasis = g2.selectAll("circle")
That is, adding the second group of elements to a different SVG group.
The proper way to do this is to use classes to select the circles (and applying that class when you create them). So you create the features like so:
var feature = g.selectAll("circle.feature")
.data(stations, function (d) { return d.id; } )
.enter().append("circle")
.attr("class", "feature") // <- assign the class
....
Similarly, for the emphasis:
var feature = g.selectAll("circle.emphasis")
.data(stations, function (d) { return d.id; } )
.enter().append("circle")
.attr("class", "emphasis") // <- assign the class
....
I've finally (sort of) figured it out. The two sets of data are treated as one because they share the same key, according to the rules of D3 constancy. So an easy way around is to give each set a key that can't overlap:
var feature = g.selectAll("circle")
.data(stations, function (d) { return d.id; } )
.enter().append("circle")
.style("stroke", "black")
.style("opacity", .6)
.style("fill", "red")
.attr("r", function(d, i) { return d.free_bikes * 1; });
var emphasis = g.selectAll("notathing")
.data(stations, function (d) { return d.id + " cannot possibly overlap"; } )
.enter().append("circle")
.style("stroke", "black")
.style("opacity", .6)
.style("fill", "blue")
.attr("r", function(d, i) { return d.free_bikes * 1; });
The only slight quirk is I have to modify the second selector (g.selectAll("notathing")) so it doesn't match any of the circles created by the first one.
So I have the next force layout graph code for setting nodes, links and other elements:
var setLinks = function ()
{
link = visualRoot.selectAll("line.link")
.data(graphData.links)
.enter().append("svg:line")
.attr("class", "link")
.style("stroke-width", function (d) { return nodeStrokeColorDefault; })
.style("stroke", function (d) { return fill(d); })
.attr("x1", function (d) { return d.source.x; })
.attr("y1", function (d) { return d.source.y; })
.attr("x2", function (d) { return d.target.x; })
.attr("y2", function (d) { return d.target.y; });
graphData.links.forEach(function (d)
{
linkedByIndex[d.source.index + "," + d.target.index] = 1;
});
};
var setNodes = function ()
{
node = visualRoot.selectAll(".node")
.data(graphData.nodes)
.enter().append("g")
.attr("id", function (d) { return d.id; })
.attr("title", function (d) { return d.name; })
.attr("class", "node")
.on("click", function (d, i) { loadAdditionalData(d.userID, this); })
.call(force.drag)
.on("mouseover", fadeNode(.1)).on("mouseout", fadeNode(1));
};
//append the visual element to the node
var appendVisualElementsToNodes = function ()
{
node.append("circle")
.attr("id", function (d) { return "circleid_" + d.id; })
.attr("class", "circle")
.attr("cx", function (d) { return 0; })
.attr("cy", function (d) { return 0; })
.attr("r", function (d) { return getNodeSize(d); })
.style("fill", function (d) { return getNodeColor(d); })
.style("stroke", function (d) { return nodeStrokeColorDefault; })
.style("stroke-width", function (d) { return nodeStrokeWidthDefault; });
//context menu:
d3.selectAll(".circle").on("contextmenu", function (data, index)
{
d3.select('#my_custom_menu')
.style('position', 'absolute')
.style('left', d3.event.dx + "px")
.style('top', d3.event.dy + "px")
.style('display', 'block');
d3.event.preventDefault();
});
//d3.select("svg").node().oncontextmenu = function(){return false;};
node.append("image")
.attr("class", "image")
.attr("xlink:href", function (d) { return d.profile_image_url; })//"Images/twitterimage_2.png"
.attr("x", -12)
.attr("y", -12)
.attr("width", 24)
.attr("height", 24);
node.append("svg:title")
.text(function (d) { return d.name + "\n" + d.description; });
};
Now, the colors and size dependencies changed and I need to redraw the graph circles (+all appended elements) with different color and radius. Having problem with it.
I can do this:
visualRoot.selectAll(".circle").remove();
but I have all the images that I attached to '.circles' still there.
In any way, any help will be appreciated, let me know if the explanation is not clear enough, I will try to fix it.
P.S. what is the difference between graphData.nodes and d3.selectAll('.nodes')?
Your answer will work, but for posterity, these methods are more generic.
Remove all children from HTML:
d3.select("div.parent").html("");
Remove all children from SVG/HTML:
d3.select("g.parent").selectAll("*").remove();
The .html("") call works with my SVG, but it might be a side effect of using innerSVG.
If you want to remove the element itself, just use element.remove(), as you did. In case you just want to remove the content of the element, but keep the element as-is, you can use f.ex.
visualRoot.selectAll(".circle").html(null);
visualRoot.selectAll(".image").html(null);
instead of .html("") (I wasn't sure which element's children you want deleted). This keeps the element itself, but cleans all included content. It the official way to do this, so should work cross-browser.
PS: you wanted to change the circle sizes. Have you tried
d3.selectAll(".circle").attr("r", newValue);
My first advice is that you should read the d3.js API about selections: https://github.com/mbostock/d3/wiki/Selections
You have to understand how the enter() command works (API). The fact that you have to use it to handle new nodes has a meaning which will help you.
Here is the basic process when you deal with selection.data():
first you want to "attach" some data to the selection. So you have:
var nodes = visualRoot.selectAll(".node")
.data(graphData.nodes)
Then you can modify all nodes each times data is changed (this will do exactly what you want). If for example you change the radius of old nodes which are in the new dataset you loaded
nodes.attr("r", function(d){return d.radius})
Then, you have to handle new nodes, for this you have to select the new nodes, this is what selection.enter() is made for:
var nodesEnter = nodes.enter()
.attr("fill", "red")
.attr("r", function(d){return d.radius})
Finally you certainly want to remove the nodes you don't want anymore, to do this, you have to select them, this is what selection.exit() is made for.
var nodesRemove = nodes.exit().remove()
A good example of the whole process can also be found on the API wiki: https://github.com/mbostock/d3/wiki/Selections#wiki-exit
in this way, I have resolved it very easily,
visualRoot.selectAll(".circle").remove();
visualRoot.selectAll(".image").remove();
and then I just re-added visual elements which were rendered differently because the code for calculating radius and color had changed properties. Thank you.
To remove all element from a node:
var siblings = element.parentNode.childNodes;
for (var i = 0; i < siblings.length; i++) {
for (var j = 0; j < siblings.length; j++) {
siblings[i].parentElement.removeChild(siblings[j]);
}
}`