d3 drawing arrows tips - d3.js

In this example :
http://jsfiddle.net/maxl/mNmYH/2/
If I enlarge the circles, ex:
var radius = 30; // (is 6 in the jsFiddle)
var circle = svg.append("svg:g").selectAll("circle")
.data(force.nodes())
.enter().append("svg:circle")
.attr("r", radius)
What is the best way to properly adjust the drawing of the arrow
so that it points to the radius of the circle ?
Thanks

You asked for the "best way to properly adjust the drawing of the arrow ".
I cannot claim the following approach is the "best" way, and I look forward to other answers, but here is one method to tackle this issue.
http://jsfiddle.net/Y9Qq3/2/
Relevant updates are noted below.
...
var w = 960,
h = 500
markerWidth = 6,
markerHeight = 6,
cRadius = 30, // play with the cRadius value
refX = cRadius + (markerWidth * 2),
refY = -Math.sqrt(cRadius),
drSub = cRadius + refY;
...
svg.append("svg:defs").selectAll("marker")
.data(["suit", "licensing", "resolved"])
.enter().append("svg:marker")
.attr("id", String)
.attr("viewBox", "0 -5 10 10")
.attr("refX", refX)
.attr("refY", refY)
.attr("markerWidth", markerWidth)
.attr("markerHeight", markerHeight)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5");
...
function tick() {
path.attr("d", function (d) {
var dx = d.target.x - d.source.x,
dy = (d.target.y - d.source.y),
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + (dr - drSub) + "," + (dr - drSub) + " 0 0,1 " + d.target.x + "," + d.target.y;
});
...

Related

Is it possible to create an SVG rect element with top left and top right rounded corners for use in D3? [duplicate]

This question already has answers here:
svg / d3.js rounded corners on one side of a rectangle
(5 answers)
Closed 6 years ago.
Is there a simple way to place rounded corners just on the top of the Bar(s) in a D3 Vertical Bar Chart? I've been playing around with .attr("rx", 3) and that seems to affect all four corners of a Bar.
You cannot specify which corners you want to make round in SVG: rx will affect all 4 corners.
The only solution is using a path for simulating a rectangle. This function returns a path with top corners round:
function rectangle(x, y, width, height, radius){
return "M" + (x + radius) + "," + y + "h" + (width - 2*radius)
+ "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius + "v" +
(height - 2*radius) + "v" + radius + "h" + -radius + "h" +
(2*radius - width) + "h" + -radius + "v" + -radius + "v" +
(2*radius - height) + "a" + radius + "," + radius + " 0 0 1 "
+ radius + "," + -radius + "z";
};
Here is a demo snippet showing a "bar chart" with those paths, with a radius (the rx equivalent here) of 5px:
function rectangle(x, y, width, height, radius){
return "M" + (x + radius) + "," + y + "h" + (width - 2*radius) + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + radius + "v" + (height - 2*radius) + "v" + radius + "h" + -radius + "h" + (2*radius - width) + "h" + -radius + "v" + -radius + "v" + (2*radius - height) + "a" + radius + "," + radius + " 0 0 1 " + radius + "," + -radius + "z";
};
var data = [40, 50, 30, 40, 90, 54, 20, 35, 60, 42];
var svg = d3.select("body")
.append("svg")
.attr("width", 400)
.attr("height", 120);
var rects = svg.selectAll(".paths").data(data).enter().append("path");
rects.attr("d", function(d,i){ return rectangle(10+40*i,100-d,20,d,5)});
var texts = svg.selectAll(".text").data("ABCDEFGHIJ".split("")).enter().append("text").attr("y",114).attr("x", function(d,i){return 16+40*i}).text(function(d){return d});
path {
fill:teal;
}
text {
fill:darkslategray;
font-size: 12px;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
PS: I didn't write that function, it was based on these answers by M. Bostock and R. Longson.

display axes in a circle with equal spacing in between

As you can see from this example by Mike Bostock, it is possible to display the axis to a graph in a circle. In the linked to example, there are three axis (with the areas in between of equal size) which seemed to be created by this line of code
var angle = d3.scale.ordinal().domain(d3.range(4)).rangePoints([0, 2 * Math.PI]),
plus
svg.selectAll(".axis")
.data(d3.range(3))
.enter().append("line")
.attr("class", "axis")
.attr("transform", function(d) { return "rotate(" + degrees(angle(d)) + ")"; })
.attr("x1", radius.range()[0])
.attr("x2", radius.range()[1]);
Playing around with that example, I was able to create a graph with six axes (with equal spacing between each axis) that covered the whole circle using this code
var angle = d3.scale.ordinal().domain(["one", "two", "three", "four", "five", "six"]).range([0, 45, 90, 135, 180, 225])
and then
svg.selectAll(".axis").data(d3.range(7))
//code omitted
However, I haven't been able to create a circle with 9 axes (with equal spacing in between) by doing this (as I expected it would)
var angle = d3.scale.ordinal()
.domain(["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"])
.range([0, 45, 90, 135, 180, 225, 270, 315, 360]);
svg.selectAll(".axis").data(d3.range(10))
//code omitted
The result of doing this is that the axes start to go around the circle a second time.
Question: is there a pattern that can be followed to have an arbitrary number of axes displayed in a circle with equal spacing in between each? If so, please explain the d3 principles behind the two successful attempts and the one unsuccessful attempt shown and linked to above.
Update
Although removing the calls to degrees, puts the axes in the right position, (and then removing the call to degrees in the nodes code puts the nodes on the axes in the right axes), the links are not lining up properly i.e. they are not starting and ending on the axes, but rather floating unanchored. You can see the problem in this image
This is the code for the links (notice that it doesn't have a call to degrees)
svg.selectAll(".link")
.data(linx)
.enter().append("path")
.attr("class", "link")
.attr("class", function(d) { return "link " + d.Class})
.attr("d", link()
.angle(function(d) { return angle(d.X); })
.radius(function(d) { return radius(d.Y); }))
.on("mouseover", linkMouseover)
.on("mouseout", mouseout);
It calls a link function (which also doens't have a call to degrees, so I don't know why the links are starting and ending at the old position of the axes) that I got from Mike Bostock's hive implementation
function link() {
var source = function(d) { return d.Source; },
target = function(d) { return d.Target; },
angle = function(d) { return d.angle; },
startRadius = function(d) { return d.radius; },
endRadius = startRadius,
arcOffset = -Math.PI / 2;
function link(d, i) {
// console.log(d, i, "interior link func");
var s = node(source, this, d, i),
t = node(target, this, d, i),
x;
if (t.a < s.a) x = t, t = s, s = x;
if (t.a - s.a > Math.PI) s.a += 2 * Math.PI;
var a1 = s.a + (t.a - s.a) / 3,
a2 = t.a - (t.a - s.a) / 3;
return s.r0 - s.r1 || t.r0 - t.r1
? "M" + Math.cos(s.a) * s.r0 + "," + Math.sin(s.a) * s.r0
+ "L" + Math.cos(s.a) * s.r1 + "," + Math.sin(s.a) * s.r1
+ "C" + Math.cos(a1) * s.r1 + "," + Math.sin(a1) * s.r1
+ " " + Math.cos(a2) * t.r1 + "," + Math.sin(a2) * t.r1
+ " " + Math.cos(t.a) * t.r1 + "," + Math.sin(t.a) * t.r1
+ "L" + Math.cos(t.a) * t.r0 + "," + Math.sin(t.a) * t.r0
+ "C" + Math.cos(a2) * t.r0 + "," + Math.sin(a2) * t.r0
+ " " + Math.cos(a1) * s.r0 + "," + Math.sin(a1) * s.r0
+ " " + Math.cos(s.a) * s.r0 + "," + Math.sin(s.a) * s.r0
: "M" + Math.cos(s.a) * s.r0 + "," + Math.sin(s.a) * s.r0
+ "C" + Math.cos(a1) * s.r1 + "," + Math.sin(a1) * s.r1
+ " " + Math.cos(a2) * t.r1 + "," + Math.sin(a2) * t.r1
+ " " + Math.cos(t.a) * t.r1 + "," + Math.sin(t.a) * t.r1;
}
function node(method, thiz, d, i) {
var node = method.call(thiz, d, i),
a = +(typeof angle === "function" ? angle.call(thiz, node, i) : angle) + arcOffset,
r0 = +(typeof startRadius === "function" ? startRadius.call(thiz, node, i) : startRadius),
r1 = (startRadius === endRadius ? r0 : +(typeof endRadius === "function" ? endRadius.call(thiz, node, i) : endRadius));
return {r0: r0, r1: r1, a: a};
}
link.source = function(_) {
if (!arguments.length) return source;
source = _;
return link;
};
link.target = function(_) {
if (!arguments.length) return target;
target = _;
return link;
};
link.angle = function(_) {
if (!arguments.length) return angle;
angle = _;
return link;
};
link.radius = function(_) {
if (!arguments.length) return startRadius;
startRadius = endRadius = _;
return link;
};
link.startRadius = function(_) {
if (!arguments.length) return startRadius;
startRadius = _;
return link;
};
link.endRadius = function(_) {
if (!arguments.length) return endRadius;
endRadius = _;
return link;
};
return link;
}
You have angles in degrees already, you don't need to use the degree() function. If you remove the call to that everything will work fine.

d3Js - how to arrange my values as around the 360d and automate data in a circle?

I have a data like this:
var requiredDegrees = [0,30,60,90,120,150,180,210,240,270,300,330,360];
I would like to arrange this data in a cirlce around. how to calculate and palace the degrees across my circle.
And I would like to create the same as like this http://windhistory.com/station.html?KCFE by 3d.js any one suggest me the correct way here please?
Simplest example I can code up:
var requiredDegrees = [0, 30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360];
var diameter = 300;
var svg = d3.select("body").append("svg")
.attr("width", diameter + 50)
.attr("height", diameter + 50)
.append("g")
.attr("transform", "translate(25,25)");
svg.append("circle")
.attr("transform", "translate(" + diameter / 2 + "," + diameter / 2 + ")")
.attr("r", diameter / 2)
svg.selectAll('text')
.data(requiredDegrees)
.enter()
.append('text')
.text(function(d) {
return d;
})
.attr('transform', function(d) {
return "translate(" + diameter / 2 + "," + 0 + ") rotate(" + d + ",0," + diameter / 2 + ")";
});
Demonstration here.

D3 placing nodes labels inside circles in Mobile Patent Suits

I'm new to D3 and I'm using this template (http://bl.ocks.org/mbostock/1153292) to visualize my graph. However, my nodes' labels are shore and I want to place them inside circles not on their right hand-side.
Can anybody help me with that?
Thanks a lot
Append circle and text inside a group element and use text-achor property to align the text to the middle.
var nodes = svg.selectAll(".node")
.data(force.nodes())
.enter()
.append("g")
.attr("class","node")
.call(force.drag);
var circles = nodes.append("circle")
.attr("r", 6);
var texts = nodes.append("text")
.attr("text-anchor", "middle")
.text(function(d) {
return d.name;
});
Change tick function as shown below.
function tick() {
path.attr("d", linkArc);
nodes.attr("transform", transform);
}
Update
JSFiddle 1 for aligning text to the center.
If you would like enclose the text label within the circle, increase the radius of circle using the length of name property. Note that, you will have to update the link target positions this time, to adjust the marker positions relative to the circle radius.
var circles = nodes.append("circle")
.attr("r", function(d){ d.radius = d.name.length*3; return d.radius; }
);
function linkArc(d) {
var tX = d.target.x-d.target.radius,
dx = tX - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + tX + "," + d.target.y;
}
JSFiddle 2

arrows on links in d3js force layout

I'm using the force layout to represent a directed unweighted network. My inspiration comes from the following example: http://bl.ocks.org/mbostock/1153292
I tried to make nodes of different sizes, but I have a little problem.
The marker used to draw the arrow on each link points to the center of the circle. If the circle is too big it covers completely the arrow.
How can I handle this?
If you will use a <line> instead of <path>, the following should work for you, I have it working in my current solution. It's based on #ɭɘ ɖɵʊɒɼɖ 江戸 solution:
In your tick event listener:
linkElements.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) {
return getTargetNodeCircumferencePoint(d)[0];
})
.attr("y2", function(d) {
return getTargetNodeCircumferencePoint(d)[1];
});
function getTargetNodeCircumferencePoint(d){
var t_radius = d.target.nodeWidth/2; // nodeWidth is just a custom attribute I calculate during the creation of the nodes depending on the node width
var dx = d.target.x - d.source.x;
var dy = d.target.y - d.source.y;
var gamma = Math.atan2(dy,dx); // Math.atan2 returns the angle in the correct quadrant as opposed to Math.atan
var tx = d.target.x - (Math.cos(gamma) * t_radius);
var ty = d.target.y - (Math.sin(gamma) * t_radius);
return [tx,ty];
}
I am sure this solution can be modified to accomodate <path> elements, however I haven't tried it.
You can offset the target of the link by the radius of the node, i.e. adjust the code
path.attr("d", function(d) {
var dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy);
return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
});
by changing the values of d.target.x and d.target.y to take the radius (which would need to be part of the data, something like d.target.radius) into account. That is, offset the end of the arrow by the circle radius.
At the end I've decided to create a marker for each link (instead of one per class).
This solution has the advantage of defining the offset of each marker, depending on the target node which, in my own case, is refX.
// One marker for link...
svg.append("svg:defs").selectAll("marker")
.data(force.links())
.enter().append("svg:marker")
.attr("id", function(link, idx){ return 'marker-' + idx})
.attr("viewBox", "0 -5 10 10")
.attr("refX", function(link, idx){
return 10 + link.target.size;
})
.attr("refY", 0)
.attr("markerWidth", 6)
.attr("markerHeight", 6)
.attr("orient", "auto")
.append("svg:path")
.attr("d", "M0,-5L10,0L0,5")
.attr("fill", function(link){
if(link.type == 'in')
return "green";
return "blue";
});
Now there is one little problem with the fact that the line is curve. This means that the marker/arrow should be translated not only on the X axis, but also on the Y axis, of a value which probably depends on the ray of the curve...
A bit late to answer, but combining all previous answers, I have come up with a comprehensive solution that works for me in d3 v4, written in TypeScript because Angular (in case you find the lack of global variables curious). Below is a snippet containing the key components to include (because my entire production code is way too long and under NDA). Key ideas are annotated as code comments. The end result looks like this:
First of all, since you have tried to make nodes of different sizes, I will assume you have a radius property inside your nodes data. Let's say it is an array of objects like this:
{
id: input.name,
type: input.type,
radius: input.radius
}
Then markers are appended. Note that the size of each arrow (or marker) is 10, and half of it is 5. You can assign it as a variable like #ɭɘ-ɖɵʊɒɼɖ-江戸 did in his answer, but I am just too lazy.
let marker = svg.append("defs")
.attr("class", "defs")
.selectAll("marker")
// Assign a marker per link, instead of one per class.
.data(links, function (d) { return d.source.id + "-" + d.target.id; });
// Update and exit are omitted.
// Enter
marker = marker
.enter()
.append("marker")
.style("fill", "#000")
// Markers are IDed by link source and target's name.
// Spaces stripped because id can't have spaces.
.attr("id", function (d) { return (d.source.id + "-" + d.target.id).replace(/\s+/g, ''); })
// Since each marker is using the same data as each path, its attributes can similarly be modified.
// Assuming you have a "value" property in each link object, you can manipulate the opacity of a marker just like a path.
.style("opacity", function (d) { return Math.min(d.value, 1); })
.attr("viewBox", "0 -5 10 10")
// refX and refY are set to 0 since we will use the radius property of the target node later on, not here.
.attr("refX", 0)
.attr("refY", 0)
.attr("markerWidth", 5)
.attr("markerHeight", 5)
.attr("orient", "auto")
.append("path")
.attr("d", "M0,-5L10,0L0,5")
.merge(marker);
Then, the path can reference each individual marker with its ID:
let path = svg.append("g")
.attr("class", "paths")
.selectAll("path")
.data(links, function (d) { return d.source.id + "-" + d.target.id; });
// Update and exit are omitted.
// Enter
path = path
.enter()
.append("path")
.attr("class", "enter")
.style("fill", "none")
.style("stroke", "#000")
.style("stroke-opacity", function (d) { return Math.min(d.value, 1); })
// This is how to connect each path to its respective marker
.attr("marker-end", function(d) { return "url(#" + (d.source.id + "-" + d.target.id).replace(/\s+/g, '') + ")"; })
.merge(path);
One optional thing to modify if you want more features: Allow your .on("tick", ticked) listener to receive more variables to test for boundaries. For example, the width and height of the svg.
.on("tick", function () { ticked(node, path, width, height) })
And here is your new ticked function, based on the answer of #ɭɘ-ɖɵʊɒɼɖ-江戸 :
ticked(node, path, width, height) {
node
.attr("transform", function(d){return "translate(" + Math.max(d.radius, Math.min(width - d.radius, d.x)) + "," + Math.max(d.radius, Math.min(height - d.radius, d.y)) + ")"});
path
.attr("d", d => {
let dx = d.target.x - d.source.x,
dy = d.target.y - d.source.y,
dr = Math.sqrt(dx * dx + dy * dy),
gamma = Math.atan2(dy, dx), // Math.atan2 returns the angle in the correct quadrant as opposed to Math.atan
sx = Math.max(d.source.radius, Math.min(width - d.source.radius, d.source.x + (Math.cos(gamma) * d.source.radius) )),
sy = Math.max(d.source.radius, Math.min(height - d.source.radius, d.source.y + (Math.sin(gamma) * d.source.radius) )),
// Recall that 10 is the size of the arrow
tx = Math.max(d.target.radius, Math.min(width - d.target.radius, d.target.x - (Math.cos(gamma) * (d.target.radius + 10)) )),
ty = Math.max(d.target.radius, Math.min(height - d.target.radius, d.target.y - (Math.sin(gamma) * (d.target.radius + 10)) ));
// If you like a tighter curve, you may recalculate dx dy dr:
//dx = tx - sx;
//dy = ty - sy;
//dr = Math.sqrt(dx * dx + dy * dy);
return "M" + sx + "," + sy + "A" + dr + "," + dr + " 0 0,1 " + tx + "," + ty;
});
}
As mentioned by #joshua-comeau, it should be a plus sign when calculating sx and sy.
Here my solution :
First I calculate the angle with horizontal axes of the path (gamma). Then I get the X component (Math.cos(gamma) * radius) and Y component (Math.sin(gamma) * radius) of the radius. Then offset the ends of the path by those components.
function linkArc(d) {
var t_radius = calcRadius(d.target.size);
var s_radius = calcRadius(d.source.size);
var dx = d.target.x - d.source.x;
var dy = d.target.y - d.source.y;
var gamma = Math.atan(dy / dx);
var tx = d.target.x - (Math.cos(gamma) * t_radius);
var ty = d.target.y - (Math.sin(gamma) * t_radius);
var sx = d.source.x - (Math.cos(gamma) * s_radius);
var sy = d.source.y - (Math.sin(gamma) * s_radius);
return "M" + sx + "," + sy + "L" + tx + "," + ty;
}
First you will notice I am not using arcs but the principle should be the same.
Also my nodes have a size property from which I calculate the diameter of the circle.
Finally my marker is defined as is:
var arrowsize = 10;
var asHalf = arrowsize / 2;
svg.append("defs").selectAll("marker")
.data(["arrowhead"])
.enter().append("marker")
.attr("id", function (d) {
return d;
})
.attr("viewBox", "0 -5 " + arrowsize + " " + arrowsize)
.attr("refX", arrowsize)
.attr("refY", 0)
.attr("markerWidth", 9)
.attr("markerHeight", 9)
.attr("orient", "auto")
.attr("class", "arrowhead-light")
.append("path")
.attr("d", "M 0," + (asHalf * -1) + " L " + arrowsize + ",0 L 0," + asHalf);
I haven't found a way to control every single copy of the marker.

Resources