.style of child nodes in d3js - svg

I'm trying to make a simple graph with nodes and links. I have "g" elements containing a circle and its text, and links on their own. I have, for example, this bit on code called on a mouseover event:
//check if circle is connected to current "viewed" (mouseover-ed)
//circle via a link referenced by "that" and paint it green if so
circles.filter(function() {
return d3.select(this).attr("index") == d3.select(that).attr("src");
}).attr("viewed",1).style("stroke", "green");
});
This was really a long shot as nodes is the 'g' element container and I wasn't sure what calling .style would do, but to my surprise it did change the color - but only for the text!
Is there a way to make it change the stroke style of the circle as well?
The declaration code:
var circles = svg.append("g")
.attr("class","nodes")
.selectAll("circle")
.data(graph.nodes)
.enter()
.append("g")
.attr("transform",function(d,i){d.x = getX(i);d.y=getY(i);return "translate(" + d.x + "," + d.y + ")";})
.attr("name", function(d){return d.name;})
.attr("viewed", 0)
.attr("focused", 0)
.attr("index", function(d, i) {return i;});
circles.append("circle")
.style("stroke", "gray")
.style("fill", "white")
.attr("r", node_radius_wo_pad)
.on("mouseover", function(){...};
circles.append("text")
.attr("text-anchor","middle")
.text(function(d){return d.name});

The reason this is working is that you haven't explicitly declared a stroke colour for the text and so it inherits what you set for the parent g element. To make this work for the circles, you have to select them explicitly:
var toChange = circles.filter(function() {
return d3.select(this).attr("index") == d3.select(that).attr("src");
});
toChange.attr("viewed", 1);
toChange.selectAll("circle").style("stroke", "green");
toChange.selectAll("text").style("stroke", "green");

Related

SVG g hides when parent g is set to a height

I am relatively new to SVG. I am plotting a chart which will dynamically plot temperature or wind value on x,y axis respectively. I am good with x-axis positioning.
But when it comes to Y-Axis, position come right but if the value is higher than parent chart height, it get cut off as you can see in the picture.
Need help on how to force visible the circle/element even it exceeds the parent element width or height?
Here is how mark up gets generated
I am using d3.js for this.
Here is the code for generating circle with text
let svg = container
.append("svg")
.attr("width", width)
.attr("height", height+(height*0.7));
const chart = svg
.append("g")
.attr('class','chartwind')
.attr("transform", "translate(" + padding.left + "," + (padding.top) + ")")
chart.append("path")
.data(datapoints)
.attr("class", "line wind-line")
.style("stroke", colorScale("wind"))
.style('stroke-width', '2px')
.attr("d", windLine)
let windPoint = chart.selectAll('g.windpoint').data(datapoints).enter().append('g').attr('class', 'windpoint').attr('transform', function (d) {
return 'translate(' + (Math.round(xScale(d.parsedUtcDateTimeNow)) - 10) + ',' + yScale(d.windSpeed) + ')';
})
chart.selectAll('.windcircle')
.data(Infos)
.enter().append('circle')
.attr("class", "windcircle")
.style("stroke", colorScale("wind"))
.style('stroke-width', '2px')
.attr("cx", (d) => xScale(d.parsedUtcDateTimeNow))
.attr("cy", (d) => {
return yScale(d.windSpeed);
})
.attr('r', 3)
.style("fill", colorScale("wind"))
windPoint
.append('circle')
.attr("cx", 0)
.attr("cy", 0)
.attr("r", function (d) {
return 8;
})
.attr("fill", "green")
.attr("transform", "translate(0,-23)")
windPoint
.append('text')
.attr("fill", "white")
.attr("transform", "translate(0,-19)")
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.attr("font-weight", "600")
.text((d) => {
return d.windGust;
});
windPoint
.append('text')
.attr('text-anchor', 'middle')
//.attr("transform","translate(0,5)")
.text((d) => {
return d.windSpeed;
});
Update
This is how I am constructing SVG height and width
function getSizesById(id) {
const container = document.querySelector(`#${id}`)
if (!container)
return null
return {
height: container.clientHeight,
width: container.clientWidth,
}
}
const { width, height } = (() => {
return getSizesById(containerID)
})()
const { width, height } = (() => {
return getSizesById(containerID)
})(),
padding = {
...size.padding,
top: 20,
bottom: 20
},
chartHeight = height - padding.bottom - padding.top,
chartWidth = width - padding.left - padding.right
const container = d3.select(`#${containerID}`)
let svg = container
.append("svg")
.attr("width", width)
.attr("height", height);
Note: SVG height (or chart) should look with in the DIV and only when the data points go over the scale, then we need data to be visible over the div height.
<g> elements do not have any inherent size. They are only a logical wrapper for a group of markup tags, and a place to give them some common properties. What restricts the visible parts of your chart is the <svg> element.
Your code shows that each datapoint is represented by grafic elements that span a bounding box of (-8 -31 16 35) (left - top - width - height). This is how much space you need to show all of it.
Remove the transform attribute from your .chartwind group. The space you need to show the complete graph is
left: lower boundary of your xScale range minus 8
top: lower boundary of your yScale range minus 31 (in the downward coordinate system)
width: extent of your xScale range plus 16
height: extent of your yScale range plus 35
Add some padding if you like.
Add a viewBox attribute with these four numbers to the <svg> element: viewbox="<left> <top> <width> <height>". The area described like this will then be fitted inside the available space of the <svg> element, without you having to do any further figuring out of transformations.

How to translate svg g elements to cozy up with siblings?

var boxes = [[30, 45], [50, 30], [40, 30]]; // [w, h]
//Should i calculate `translate` value here, adding all heights?
var secs = wrapper.selectAll('g.section')
.data(data)
.enter()
.append('g')
.attr('class', 'section')
.attr("transform", "translate(" + 0 + "," + 'unknown' + ")");
//could be many sub-secs by a lot of data transformation before appending rect to the last one of them.
secs.append('rect')
.datum(function(d){return d;})
.attr('class', 'fragment')
.attr('x', 0)
.attr('y', 0)
.attr('width', function(d){return d[0];})
.attr('height', function(d){return d[1];})
// or here, not from data but from elem's dimensions?
secs.each(function(sec, i){
var prev = this.previousSibling?this.previousSibling.getBBox():'';
var ty = prev?prev.height+ prev.y:0;
d3.select(this).attr("transform", "translate(" + 0 + "," + ty + ")");
});
Is this how you translate g elements to fit their childrens, at any level of depth?
And i'll have to translate them manually when child expands?
i'm new at svg and d3.
Thank you.
It looks like you would need to keep track of the sum of heights and translate by that. That is, for each rectangle that you add add its height to a total which you can then use to offset subsequent elements.

Get arrowheads to point at outer edge of node in D3

I'm new to D3 and I'm trying to create an interactive network visualization. I've copied large parts of this example, but I have changed the curved lines to straight ones by using SVG "lines" rather than "paths", and I've also scaled the nodes according to the data they represent. The problem is that my arrowheads (created with SVG markers) are at the ends of the lines. Since some of the nodes are large, the arrows get hidden behind them. I'd like my arrowheads to show up right at the outside edge of the node they point to.
Here is how I'm creating the markers and links:
svg.append("svg:defs").selectAll("marker")
.data(["prereq", "coreq"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", 15)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
var link = svg.selectAll(".link")
.data(force.links())
.enter().append("line")
.attr("class", "link")
.attr("marker-end", function(d) { return "url(#" + d.type + ")"; });
I noticed that the "refX" attribute specifies how far from the end of the line the arrowhead should show up. How can I make this dependent on the radius of the node it's pointing to? If I can't do that, could I instead change the endpoints of the lines themselves? I'm guessing I would do that in this function, which resets the endpoints of the lines as everything moves:
function tick() {
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; });
circle.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
Which approach makes more sense, and how would I implement it?
Thanks Lars Kotthoff, I got this to work following the advice from the other question! First I switched from using lines to paths. I don't think I actually had to do that, but it made it easier to follow the other examples I was looking at because they used paths.
Then, I added a "radius" field to my nodes. I just did this when I set the radius attribute, by adding it as an actual field rather than returning the value immediately:
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", function(d) {
if (d.logic != null) {
d.radius = 5;
} else {
d.radius = node_scale(d.classSize);
}
return d.radius;
I then edited my tick() function to take this radius into account. This required a bit of simple geometry...
function tick(e) {
path.attr("d", function(d) {
// Total difference in x and y from source to target
diffX = d.target.x - d.source.x;
diffY = d.target.y - d.source.y;
// Length of path from center of source node to center of target node
pathLength = Math.sqrt((diffX * diffX) + (diffY * diffY));
// x and y distances from center to outside edge of target node
offsetX = (diffX * d.target.radius) / pathLength;
offsetY = (diffY * d.target.radius) / pathLength;
return "M" + d.source.x + "," + d.source.y + "L" + (d.target.x - offsetX) + "," + (d.target.y - offsetY);
});
Basically, the triangle formed by the path, it's total x change (diffX), and it's total y change (diffY) is a similar triangle to that formed by the segment of the path inside the target node (i.e. the node radius), the x change inside the target node (offsetX), and the y change inside the target node (offsetY). This means that the ratio of the target node radius to the total path length is equal to the ratio of offsetX to diffX and to the ratio of offsetY to diffY.
I also changed the refX value to 10 for the arrows. I'm not sure why that was necessary but now it seems to work!
I answered the same question over here. The answer uses vector math, it's quite useful for other calculations as well.

Putting an arrow (marker) at specific point on a path when using the d3 javascript library

I am working currently on a graph visualization and I use SVG and the D3 library. I was asked by our designer if I can put the arrowheads of the edges of the graph on a position corresponding to 80% of length of the lines.
I was able to achieve the first part - getting the position - by using the getPointAtLength method.
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
var path = svg.append("path")
.attr("d", "M20,20C400,20,20,400,400,400")
.attr("fill", "none")
.attr("stroke", "black");
var pathEl = path.node();
var pathLength = pathEl.getTotalLength();
var pathPoint = pathEl.getPointAtLength(pathLength*0.5);
var point = svg.append("svg:circle")
.style("fill", "red")
.attr("r", 5)
.attr("cx", pathPoint.x)
.attr("cy", pathPoint.y);
Here is a jsfidle example
Now I wonder how ca I attach an arrowhead to this position with corresponding orientation. More important how can I do this so I can update the edges of the graph when moving the associated nodes.
I was not able to find any answer yet, the examples on "markers" are working with path properties like : style('marker-end', "url(#end-arrow)")
Firstly, the long answer from SO. The quick answer is SVG <markers>
The (basic) short answer: Take a point a little before the red dot, measure the slope and draw a line between the two points. Now the question is simplified to: How do add an arrow to the end of a straight line? Use the quick answer.
Add this to your code to visualize the answer:-
var pathPoint2 = pathEl.getPointAtLength(pathLength*0.78);
var point2 = svg.append("svg:circle")
.style("fill", "blue")
.attr("r", 3)
.attr("cx", pathPoint2.x)
.attr("cy", pathPoint2.y);
var slope = (pathPoint.y - pathPoint2.y)/(pathPoint.x - pathPoint2.x);
var x0 = pathPoint2.x/2;
var y0 = slope*(x0 - pathPoint.x) + pathPoint.y;
var line = svg.append("svg:path")
.style("stroke","green")
.attr("d", "M" + pathPoint.x + "," + pathPoint.y + " L" + x0 +","+ y0);

Fade/change the color of an SVG Shape over time after being added to a canvas?

I have created an SVG map that plots tweets live containing particular keywords. I'm drawing each tweet to the screen as a circle (or dot), and after 50 tweets have been added to the map, the oldest one will disappear.
I'd like to have some sort of color decay for the circles depending on how long they've been on the map.
New tweets would pop onto the map and be red. As time passes, points already plotted on the map will slowly fade to black.
Here's where I add the circles to the map:
function mapTweet(tweetData) {
var tipText; // Ignore this. For tweet dot hovering.
var coordinates = projection([tweetData.geo.coordinates[1], tweetData.geo.coordinates[0]]);
addCircle(coordinates, tipText);
}
function addCircle(coordinates, tipText, r) {
tweetNumber++;
// too many tweets
if (tweetNumber == 50) {
tweetNumber = 0;
}
//removes expired circles
$('#' + tweetNumber).remove();
var rad;
//determine if radius size needs to be bumped
if (arguments.length == 3) {
rad = r;
} else {
rad = 3;
}
// add radar-style ping effect
map.append('svg:circle')
.style("stroke", "rgba(255,49,49,.7)")
.style("stroke-width", 1)
.style("fill", "rgba(0,0,0,0)")
.attr('cx', coordinates[0])
.attr('cy', coordinates[1])
.attr('r', 3)
.transition()
.delay(0)
.duration(2000)
.attr("r", 60)
.style("stroke-width", 2)
.style("stroke", "rgba(255,49,49,0.0001)").transition().duration(2000).remove();
// add circles representing tweets
map.append('svg:circle').attr("class", "tweetCircles")
.attr("id", tweetNumber)
.style("stroke", "rgba(255,49,49,.7)")
.style("stroke-width", 1)
.style("fill", "rgba(240,49,49,1)")
.attr('cx', coordinates[0])
.attr('cy', coordinates[1])
.attr('r', rad);
addTipsy(tipText, tweetNumber); // Ignore this. For tweet dot hovering.
}
Once a circle is drawn, does it have to be redrawn to change the color? Or can dots have their attributes changed after being added to the canvas?
How can I decay the color over, say, 20 seconds?
Append an animate element as a child of the circle
.append('svg:animate')
.attr('attributeName', 'fill')
.attr('from', 'red')
.attr('to', 'blue')
.attr('dur', '20s');
This will interpolate from red to blue or whatever colours you choose.

Resources