I am trying to change the style of some svg element.
when I do this:
var circleSelected = d3.select("#circleid_2");
circleSelected.style("fill", "purple");
circleSelected.style("stroke-width", 5);
circleSelected.style("stroke", "red");
the circle is changing its style.
BUT, when i do this:
var allCircles = d3.selectAll(".circle");
allCircles.forEach(function (circle) {
circle.style("fill", "green"); //function(d) { return getNodeColor(d); }
});
it does not work with the error: Object [object SVGCircleElement] has no method 'style'
and here is my 'circle' declaration (note: it has both class and id):
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 getNodeStrokeColor(d); })
.style("stroke-width", function (d) { return getNodeStrokeWidth(d); });
What am I doing wrong here? Thanks for the help!
Try:
d3.selectAll("circle").style("fill", "green");
Or:
allCircles.style("fill", "PaleGoldenRod");
Explanation: d3.selectAll will return a selection, which can be acted upon using the functions described in this API: https://github.com/d3/d3/blob/master/API.md#selections-d3-selection
However, as soon as you do forEach, the internal variable returned each time as circle will be an actual DOM element - no longer a selection, and therefore no style function attached.
Related
So I'm new to d3 and very little experimented with vue.
What I want to do is graph the network after the data has been fetched in a vue component.
I tried to recreate some of the older codes about vue and d3 force layout, and tried to adapt this example, but none of them worked out and I don't really know why.
The closest I got to what I want is probably this answer, but I want it to graph after the data has been fetched.
My code looks like this right now :
<script>
import * as d3 from "d3";
export default {
name: "MapComponent",
data() {
return {
mapData: {}
};
},
created() {
this.mapdataget();
},
computed() {
this.data_vis();
},
methods: {
mapdataget: function () {
this.$store
.dispatch("mapData_get")
.then(() => {
this.mapData = this.$store.getters.mapData;
})
.catch();
},
data_vis() {
let nodes = this.mapData.nodes;
let links = this.mapData.links;
let svg = d3.select("svg")
this.simulation = d3.forceSimulation()
.force("link", d3.forceLink().id(function (d) {
return d.id;
}))
.force("charge", d3.forceManyBody())
let link = svg.append("g")
.attr("class", "links")
.selectAll("line")
.data(links) //graph.links)
.enter().append("line")
.attr("stroke-width", function (d) {
return Math.sqrt(d.value);
});
let node = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(nodes) //graph.nodes)
.enter().append("circle")
.attr("r", 5)
.call(d3.drag()
.on("start", this.dragstarted)
.on("drag", this.dragged)
.on("end", this.dragended));
node.append("title")
.text(function (d) {
return d.id;
});
this.simulation
.nodes(nodes)
.on("tick", ticked);
this.simulation.force("link")
.links(links); //graph.links);
function ticked() {
link
.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;
});
node
.attr("cx", function (d) {
return d.x;
})
.attr("cy", function (d) {
return d.y;
});
}
}
}
}
</script>
with mapData looking like this :
const mapData = {
'nodes': [{
'id':String
}, and more],
'links': [{
'id':String,
'source': sourceNodeId,
'target': targetNodeId
}, and more]
}
and the vue template is an svg :
<template>
<svg class='svg'></svg>
</template>
And I got an error :
[Vue warn]: Invalid value for option "computed": expected an Object,
but got Function.
In computed() you define variables that update the DOM at runtime, calling a method there without assigning a returned value or object to a variable is wrong. You should try moving this.data_vis() into the mounted() hook instead.
I created circle using D3.js. I used ng-bootstrap for Tooltip but It is not showing on svg element,
g.append("g").selectAll("circle").data(this.RecordDaily).enter().append("circle")
.attr("r", 5).attr("fill", "purple")
.attr("cx", function (d) { return x(parseTime(d.moy)); })
.attr("cy", function (d, i) { return y(d.session); })
.attr("data-toggle", "tooltip").attr("title", function (d) { return d.session })
.attr("ngbTooltip", function (d) { return d.session })
.attr("placement", "top")
Whole source code can be found here.
Requirement: I need to add Data Labels to the Line chart (aka above to the circles)
Attempt: Added
selectionCircle.append("text")
.attr(function (d) { return d.x; })
.attr(function (d) { return d.y; })
Below the line
var selectionCircle = this.sMainGroupElement2.selectAll("circle").data(dataPoints, function (d) { return d.dataId; });
Tried adding my code at various places in the original code but not working.
Try adding the following code below the existing "selectionCircle.exit().remove();" line:
this.sMainGroupElement2.selectAll("text").remove();
var selectionLabel = this.sMainGroupElement2.selectAll("circleLabel").data(dataPoints, function (d) { return d.dataId; });
selectionLabel.enter()
.append("text")
.classed(".circleLabel", true)
.text(function(d) { return d.ActualOrg; })
.attr("x", function (d) { return d.x; })
.attr("y", function (d) { return d.y-sH*0.05; })
.attr("fill", "#bebebe")
.attr("style", "font-family:calibri;font-size:" + sL * 0.04 + "px")
.attr("text-anchor", "middle")
selectionLabel.exit().remove();
It not best-pratice to remove (they should be updated instead) all elements like the first line does, but it will get you started.
I'm not really knowledgeable with Power BI, but in d3.js you would just append the text nodes in the enter statement, just like you appended the circle.
So it would look something like this:
selectionCircle.enter()
.append("circle")
.classed(".circle112", true)
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; })
.attr("r", sH * 0.02)
.attr("fill", statusColor)
.attr("stroke", "white")
.attr("stroke-width", sH * 0.015)
.append("text")
.text('some label text can also be a function') //Change this
.attr(function (d) { return d.x; })
.attr(function (d) { return d.y; });
The .enter() method of d3 iterates through the data and is used to add new elements depending on the data.
Hope this helps.
Following the County Bubbles example, it's easy to add a bubble for each county. This is how it is added in the example:
svg.append("g")
.attr("class", "bubble")
.selectAll("circle")
.data(topojson.feature(us, us.objects.counties).features
.sort(function(a, b) { return b.properties.population - a.properties.population; }))
.enter().append("circle")
.attr("transform", function(d) { return "translate(" + path.centroid(d) + ")"; })
.attr("r", function(d) { return radius(d.properties.population); })
.append("title")
.text(function(d) {
return d.properties.name
+ "\nPopulation " + formatNumber(d.properties.population);
});
However, rather than using a variable from the json file (population), I need to update the radii according to a variable which dynamically changes (so I cannot put it in the json file beforehand as was done in the example). I call updateRadii() when a county is clicked, which needs access to the FIPS.
var currFIPS,
flowByFIPS;
var g = svg.append("g");
queue()
.defer(d3.json, "us.json")
.defer(d3.csv, "census.csv", function(d) {
return {
work: +d.workplace,
home: +d.residence,
flow: +d.flow
}
})
.await(ready);
function ready(error, us, commute) {
// Counties
g.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("d", path)
.on("click", function(d) {
// Get FIPS of selected county
currFIPS = d.id;
// Filter on selected county (i.e., grab
// people who work in the selected county)
var data = commute.filter(function(d) {
return d.work == currFIPS;
});
// Create d3.map for where these people live
flowByFIPS = d3.map(data, function(d) {
return d.home;
});
// Update radii at "home" counties to reflect flow
updateRadii();
});
// Bubbles
g.append("g")
.attr("class", "counties")
.selectAll("circle")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("circle")
.attr("id", function(d) { return d.id; })
.attr("transform", function(d) {
return "translate(" + path.centroid(d) + ")";
})
.attr("r", 0); // invisible before a county is clicked
}
function updateRadii() {
svg.selectAll(".counties circle")
.transition()
.duration(300)
.attr("r", function(d) {
return flowByFIPS.get(d.id).flow
});
}
According to the error code, I believe that the circles do not have an id (FIPS code) attached. How do I get them to have an id? (I tried nesting the circle with the path using .each as explained in this answer, but could not get it working.)
Note that the above code works for updating fill on paths (rather than circles). For example, sub updateRadii(); for updateFill(); with the function as:
function updateFill() {
svg.selectAll(".counties path")
.transition()
.duration(300)
.attr("fill", function(d) {
return flowByFIPS.get(d.id).color; // e.g., "#444"
});
}
The problem here is that you don't supply d3 with data in the update function. I will recommend you update the data loaded from the file on the clicks, and from there you update the svg.
var update = function() {
g.selectAll(".country")
.data(data)
.attr("r", function(d) { return d.properties.flow_pct });
};
var data = topojson.feature(us, us.objects.counties).features;
data.forEach(function(x) { x.properties.flow_pct = /* calc the value */; })
g.append("g")
.attr("class", "counties")
.selectAll(".country")
.data(data)
.enter()
.append("circle")
.attr("class", "country")
.attr("transform", function(d) {
return "translate(" + path.centroid(d) + ")";
})
.on("click", function(d) {
// more code
data.forEach(function(x) { x.properties.flow_pct = /* calc the NEW value */; })
update();
});
update();
I've tried to use as much as the same code as before, but still trying to straiten it a bit out. The flow is now more d3-like, since the update function works on the changed data.
Another plus which this approach is both first render and future updates use the same logic for finding the radius.
It turns out to be an obvious solution. I forgot to check for the cases where a flow doesn't exist. The code above works if updateRadii() is changed to:
function updateRadii() {
svg.selectAll(".counties circle")
.transition()
.duration(300)
.attr("r", function(d) {
if (currFIPS == d.id) {
return 0;
}
var county = flowByFIPS.get(d.id);
if (typeof county === "undefined") {
return 0;
} else {
return county.flow;
}
});
}
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]);
}
}`