I'm using d3.js to create a donut chart with labels on the outside. Using some trigonometry based on the centroids of each slice of the pie, I position the labels.
g.append("g")
.attr("class", "percentage")
.append("text")
.attr("transform", function(d)
{
var c = arc.centroid(d);
var x = c[0];
var y = c[1];
var h = Math.sqrt(x*x + y*y);
return "translate(" + (x/h * obj.labelRadius) + ',' + (y/h * obj.labelRadius) + ")";
}
)
.attr("dy", ".4em")
.attr("text-anchor", function(d)
{
return (d.endAngle + d.startAngle)/2 > Math.PI ? "end" : "start";
}
)
.text(function(d) { return d.data.percentage+"%"; });
What I'm ultimately trying to accomplish is to rearrange labels that are outside the edges of the pie chart, to prevent overlaps.
One of the ways I have tried to solve the problem is to define set "anchor points", where labels can be positioned, guaranteeing that they will no overlap. Problem is mapping the centroids to the anchors and preserving some sense of visual correspondence between the slices and the labels (Specially difficult when slices are slim).
Image above shows the possible location of the anchors (centroids of the slices shown). With these positions it is impossible to have an overlap.
Adding complexity to the problem is the fact that when labels (they're horizontal) are close to the top or bottom of the pie, they are more easily overlapped, than when they are on the right or left of the pie.
Any ideas on how to approach this problem?
[EDIT] Following the suggestion of meetamit, I implemented the following:
.attr("dy", function(d)
{
var c = arc.centroid(d);
var x = c[0];
var y = c[1];
var h = Math.sqrt(x*x + y*y);
var dy = y/h * obj.labelRadius;
dy=dy*fontSizeParam*.14/heightParam);
return (dy)+"em";
})
It helps a bit, and gives some room to the labels, still looking for a solution that will cover all cases though...
Can't you create two arcs? one for the chart, and one for the labels?
// first arc used for drawing the pie chart
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
// label attached to first arc
g.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
// second arc for labels
var arc2 = d3.svg.arc()
.outerRadius(radius + 20)
.innerRadius(radius + 20);
// label attached to second arc
g.append("text")
.attr("transform", function(d) { return "translate(" + arc2.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function(d) { return d.data.age; });
There is a good, pragmatic d3.js-based solution by programmer John Williams presented here:
https://www.safaribooksonline.com/blog/2014/03/11/solving-d3-label-placement-constraint-relaxing/
It should work well for cases with reasonable restrictions, e.g. a maximum of 12 labels as discussed above. There are also pointers in the article to more advanced algorithms, but this simple approach may actually, when used with sufficient label-content constraints, give results that have a more orderly visual appearance than other methods would yield.
Related
I'm moving an element from one point to another. But specifically I want to achieve this animation:
http://carto.net/svg/samples/path_animation.svg
My knowledge in d3.js are somewhat limited, I do not know how to generate this curve line and I also do not know how to do 3d perspective, in which the circle should appear, then be very small and grow and eventually become small until disappearing, as well As in the attached link. How can I do it?
http://jsfiddle.net/bzfs55bg/
var circle = svg.append("circle")
.attr("fill", "blue")
.attr("r", 4)
.attr("cx", centroids.ANTIOQUIA[0])
.attr("cy", centroids.ANTIOQUIA[1]);
circle.transition()
.delay(1000)
.duration(2000)
.attr("cx", centroids.BOYACA[0])
.attr("cy", centroids.BOYACA[1]);
My answer contain 3 main steps:
First, we have to create a path from point A to point B, simulating an arc. There are several ways to do that, and your question is not clear. Here, I'm using a quadratic curve:
var arc = svg.append("path")
.style("fill", "none")
.style("stroke", "yellow")
.style("stroke-width", 2)
.attr("d", "M" + centroids.ANTIOQUIA[0] + "," +
centroids.ANTIOQUIA[1] + " Q" + centroids.BOYACA[0] +
"," + centroids.ANTIOQUIA[1] + " " +
centroids.BOYACA[0] + "," + centroids.BOYACA[1]);
This path can have a colour or be transparent, it doesn't matter.
Second, we use Bostock's famous translate along path code to translate the element along that arc. I changed the function to pass the element along with the path, so we can change its size:
circle.transition()
.duration(5000)
.attrTween("transform", translateAlong(arc.node(), circle.node()));
//the second argument is the circle -----------------^
function translateAlong(path, circle) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
d3.select(circle).attr("r", circleSize(t))
//here we can change circle's size
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};
}
Finally, I'm using a linear scale to make the circle big and small again:
var circleSize = d3.scale.linear()
.domain([0, 0.5, 1])
.range([4, 10, 4]);
The domain here goes from 0 to 1 because this is the range of values the parameter t can assume.
Here is the updated fiddle: http://jsfiddle.net/zkc2wton/
Here is a second fiddle, changing the opacity at the beginning and at the end of the movement: http://jsfiddle.net/4pdusase/
How to draw a curve line between points:
//draw a line
var curveData = [{ x: centroids.ANTIOQUIA[0], y: centroids.ANTIOQUIA[1] }, { x: centroids.BOYACA[0], y: centroids.BOYACA[0] }];
//make a line function
var lineFunction = d3.svg.line()
.x(function(d) { return d.x; })
.y(function(d) { return d.y; })
.interpolate("monotone");//change it as per your choice.
//make a path
var myPath = d3.select('svg').append("path")
.attr("d", lineFunction(curveData))
.attr("stroke", "blue")
.attr("stroke-width", 2)
.attr("fill", "none");
Please refer interpolation for the curves you may like here
Further moving point along a line and disappearing.
//transition along a path
circle.transition()
.duration(10000)
.attrTween("transform", translateAlong(myPath.node()))
.style("opacity",0);//transitioning the opacity to make it vanish.
// Returns an attrTween for translating along the specified path element.
function translateAlong(path) {
var l = path.getTotalLength();
return function(d, i, a) {
return function(t) {
var p = path.getPointAtLength(t * l);
return "translate(" + p.x + "," + p.y + ")";
};
};
}
3d i don't know :(
working code here
UPDATE: New JSFIDDLE Scaling now working, ditched the defs and rect altogether and just appended the image. But still stuck on translate.
The translating is still not working on zoom. I can set the translate to say -100 for both x and y to get the non-zoomed placement correct. But, when zooming, it's of course still translating it -100 and not the larger value it would need to be to keep it in place.
Appears to need something in the code in the zoom section toward the bottom. Been messing with the part currently commented out, but no luck so far.
// .attr("transform", function(d) { return "translate(" + (d.x - v[0]) * k + "," + (d.y - v[1]) * k + ")"; })
// .attr("x", function(d) { return d.r * k; })
// .attr("y", function(d) { return d.r * k; })
.attr("width", function(d) { return d.r * k; })
.attr("height", function(d) { return d.r * k; })
Here's JSFIDDLE. I have a d3 circle packing with a raster image inside an svg rect within each node. How do you make the image scale when zooming? The container scales, but the image stays small and repeats when zoomed. Been trying to set the defs correctly, but no luck.
var defs = svg.append("defs")
// .data(nodes)
// .enter()
.append("pattern")
.attr("id", "bg")
.attr('patternUnits', 'userSpaceOnUse')
.attr('width', imageWidthHeight)
.attr('height', imageWidthHeight)
// .attr("transform", "translate(40,80)")
.append("image")
// .html("xlink:href", "img/" + function(d) { return d.image; })
.attr("xlink:href", "http://www.public-domain-photos.com/free-stock-photos-4/travel/yosemite/yosemite-meadows.jpg")
.attr('width', imageWidthHeight)
.attr('height', imageWidthHeight)
// .attr("transform", "translate(40,80)");
Also, can't get the container/image to translate into the center of the circle. I've commented those bits out for now because it screws everything up.
Have tried to apply info from these discussions, but still stuck. Thanks.
http://bl.ocks.org/mbostock/950642#graph.json
https://groups.google.com/forum/#!topic/d3-js/fL8_1BLrCyo
How to fill D3 SVG with image instead of colour with fill?
Adding elements to a D3 circle pack nodes
Answer JSFIDDLE
Got it. The trick was changing this bit of horrible:
(d.x - v[0]) * k
to this even worse bit of horrible:
(((d.x - v[0]) * (k)) - ((d.r / 2) * k))
Then the same for y.
Don't get me wrong, I'm grateful for the zoom circle pack template and the genius(es) who put it together. Thank you. It's just for someone at my noob level, the code above looks like a punishment of some kind. :)
I'm working with D3's bullet chart and am trying to figure out how to display the actual measures number just to the right of the measures rectangle. Since I want to do this for every bullet chart, I figure it'd be best to do it right in the bullet.js code. I'm rather new to D3 so any help would be much appreciated! Here is the link to Mike Bostock's bullet chart example with the bullet.js included at the bottom.
It looks like the measures code is handled in this snippet:
// Update the measure rects.
var measure = g.selectAll("rect.measure")
.data(measurez);
measure.enter().append("rect")
.attr("class", function (d, i) { return "measure s" + i; })
.attr("width", w0)
.attr("height", height / 3)
.attr("x", reverse ? x0 : 0)
.attr("y", height / 3)
.transition()
.duration(duration)
.attr("width", w1)
.attr("x", reverse ? x1 : 0);
measure.transition()
.duration(duration)
.attr("width", w1)
.attr("height", height / 3)
.attr("x", reverse ? x1 : 0)
.attr("y", height / 3);
I thought I could just add something like this after the rect is appended but I've had no such luck.
measure.enter().append("text")
.attr("dy", "1em")
.text(function (d) { return d.measurez; })
.attr("x", reverse ? x0 : 0)
.attr("y", height / 3)
.transition()
.duration(duration)
.attr("width", w1)
.attr("x", reverse ? x1 : 0);
Thank you in advance for your consideration!
You almost got it -- there're just two small things to consider. First, you can't call .enter() twice. Once the enter selection has been operated on, it's merged into the update selection and your second selection will be empty. This is fixed easily by saving the selection in a variable, but in this case I would recommend making a separate selection for the text labels.
var measureLabel = g.selectAll("text.measure")
.data(measurez);
measureLabel.enter()....;
Second, to position the text to the right of the rect, you need to take not only the position, but also the width into account when computing the position of the text element. Also, you can omit a few elements that are not relevant to text elements.
measureLabel.enter()
.append("text")
.attr("class", function(d, i) { return "measure s" + i; })
.attr("dy", "1em")
.attr("dx", "1em")
.text(String)
.attr("x", reverse ? function(d) { return w0(d) + x0(d); } : w0)
.attr("y", height / 3);
measureLabel.transition()
.duration(duration)
.attr("x", reverse ? function(d) { return w1(d) + x1(d); } : w1);
Complete example here.
I'm creating a modified version of Mike Bostock's hierarchical edge bundling diagram:
http://mbostock.github.com/d3/talk/20111116/bundle.html
but I want to make arcs which span certain groups of data, like this:
I'm currently just hardcoding the length of the arc, but I want to do it dynamically. How can I accomplish this? Here's my current code:
/* MH - USER DEFINED VARIABLES */
var chartConfig = { "Tension" : .85, "canvasSize" : 800, "dataFile" : "../data/projects.json", "linePadding" : 160, "textPadding" : 30, "arcPadding" : 5, "arcWidth" : 30 }
var pi = Math.PI;
var radius = chartConfig.canvasSize / 2,
splines = [];
var cluster = d3.layout.cluster() //Cluster is the diagram style, a node to link dendrogram dendrogram (tree diagram)
.size([360, radius - chartConfig.linePadding]); //MH - sets the size of the circle in relation to the size of the canvas
var bundle = d3.layout.bundle(); //Bundles the node link lines so that they spread at the end but keep close initially
var arcInner = radius - chartConfig.linePadding + chartConfig.arcPadding;
var arcOuter = arcInner + chartConfig.arcWidth;
var arc = d3.svg.arc().innerRadius(arcInner).outerRadius(arcOuter);
var line = d3.svg.line.radial()
.interpolate("bundle")
.tension(chartConfig.Tension) //How tightly to bundle the lines. No tension creates straight lines
.radius(function(d) { return d.y; })
.angle(function(d) { return d.x / 180 * Math.PI; });
var vis = d3.select("#chart").append("svg")
.attr("width", radius * 2)
.attr("height", radius * 2)
.attr("class","svg")
.append("g")
.attr("class","chart")
.attr("transform", "translate(" + radius + "," + radius + ")");
d3.json(chartConfig.dataFile, function(classes) {
var nodes = cluster.nodes(packages.root(classes)),
links = packages.imports(nodes),
splines = bundle(links);
var path = vis.selectAll ("path.link")
.data(links)
.enter().append("path")
.attr("class", function(d){ return "link source-" + d.source.key + " target-" + d.target.key; })
.attr("d", function(d,i){ return line(splines[i]); });
vis.selectAll("g.node")
.data(nodes.filter(function(n) { return !n.children; }))
.enter().append("g")
.attr("class", "node")
.attr("id",function(d){ return "node-" + d.key; })
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + d.y + ")"; })
.append("text")
.attr("dx", function(d) { return d.x < 180 ? chartConfig.textPadding : -chartConfig.textPadding; }) //dx Moves The text out away from the lines in a positive or negative direction, depending on which side of the axis it is on
.attr("dy", ".31em") //moves the text up or down radially around the circle
.attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.attr("transform", function(d) { return d.x < 180 ? null : "rotate(180)"; })
.text(function(d) {
textString = d.key;
textString = textString.split('_').join(' '); //MH replace underscores with spaces
return textString;
})
.on("mouseover",textOver)
.on("mouseout",textOut);
});
/* ARCS ARE HARDCODED, SHOULD BE DYNAMIC */
var arcData = [
{aS: 0, aE: 45,rI:radius - chartConfig.linePadding + chartConfig.arcPadding,rO:radius - chartConfig.linePadding + chartConfig.textPadding-chartConfig.arcPadding}
];
var arcJobsData = d3.svg.arc().innerRadius(arcData[0].rI).outerRadius(arcData[0].rO).startAngle(degToRad(1)).endAngle(degToRad(15));
var g = d3.select(".chart").append("svg:g").attr("class","arcs");
var arcJobs = d3.select(".arcs").append("svg:path").attr("d",arcJobsData).attr("id","arcJobs").attr("class","arc");
g.append("svg:text").attr("x",3).attr("dy",15).append("svg:textPath").attr("xlink:href","#arcJobs").text("JOBS").attr("class","arcText"); //x shifts x pixels from the starting point of the arc. dy shifts the text y units from the top of the arc
...
function degToRad(degrees){
return degrees * (pi/180);
}
function updateNodes(name,value){
return function(d){
if (value) this.parentNode.appendChild(this);
vis.select("#node-"+d[name].key).classed(name,value);
}
}
I've seen your json data structure here: http://mikeheavers.com/transfers/projects/data/projects.json. Firstly, in order to group the data and append the tag correctly, it'll be better to change your data like this: https://raw.github.com/gist/4172625/4de3e6a68f9721d10e0068d33d1ebb9780db4ae2/flare-imports.json to create a hirarchical structure.
We can then use the groups to draw the arcs.
First we create groups by "selectAll" and filter your nodes. Here you could add other group names of your data:
var groupData = svg.selectAll("g.group")
.data(nodes.filter(function(d) {return (d.key=='Jobs' || d.key == 'Freelance' || d.key == 'Bayard') && d.children; }))
.enter().append("group")
.attr("class", "group");
I just checked that in my case, so you'd better verify the result of the filter and make change according to your case (our data structure is a little bit different).
Now we got a list of groups. Then we'll go through the children of each group, and choose the smallest and largest x as the start and end angle. We can create a function like this:
function findStartAngle(children) {
var min = children[0].x;
children.forEach(function(d){
if (d.x < min)
min = d.x;
});
return degToRad(min);
}
And similarly a findEndAngle function by replacing min by max. Then we can create the arcs' format:
var groupArc = d3.svg.arc()
.innerRadius(arcData[0].rI)
.outerRadius(arcData[0].rO)
.startAngle(function(d){return findStartAngle(d.children);})
.endAngle(function(d){return findEndAngle(d.children);});
Then we can create arcs in "dynamic" way:
svg.selectAll("g.arc")
.data(groupData[0])
.enter().append("arc")
.attr("d", groupArc)
.attr("class", "arc")
.append("svg:text")
...;
In my case it is groupData[0], maybe you should check it in your case.
For adding tags to arcs you just need to add d.key or d.name according to the result of your selection.
The full code is available here: https://gist.github.com/4172625. Every time I get json from database so if there's no dynamic way to generic arcs I will be dead :P Hope it helps you!
I'm new to d3.js (and stackoverflow) and I'm currently working through the parallel coordinates example. I'm currently using a 2d array named 'row' for the data. Above each vertical axis is the label '0' or '1' or '2', etc. However, I'd like each vertical axis to be labeled with the text in row[0][i]. I believe the numbers 0,1,2 are coming from the datum. Any suggestions on how I may use the labels in row[0][i] instead? I suspect I'm doing something wrong that's pretty basic. Here's the relevant code. Thanks !
// Extract the list of expressions and create a scale for each.
x.domain(dimensions = d3.keys(row[0]).filter(function (d, i) {
return row[0][i] != "name" &&
(y[d] = d3.scale.linear()
.domain(d3.extent(row, function (p) { return +p[d]; }))
.range([height, 0]));
}));
// Add a group element for each dimension.
var g = svg.selectAll(".dimension")
.data(dimensions)
.enter().append("g")
.attr("class", "dimension")
.attr("transform", function (d) { return "translate(" + x(d) + ")"; });
// Add an axis and title.
g.append("g")
.attr("class", "axis")
.each(function (d) { d3.select(this).call(axis.scale(y[d])); })
.append("text")
.attr("text-anchor", "middle")
.attr("y", -9)
.text(String);//.text(String)
If you only have a controlled set of Axis (like three axis), you may just want to set them up, individually, as follows...
svg.append("text").attr("class","First_Axis")
.text("0")
.attr("x", first_x_coordinate)
.attr("y", constant_y_coordinate)
.attr("text-anchor","middle");
svg.append("text").attr("class","Second_Axis")
.text("1")
.attr("x", first_x_coordinate + controlled_offset)
.attr("y", constant_y_coordinate)
.attr("text-anchor","middle");
svg.append("text").attr("class","Third_Axis")
.text("2")
.attr("x", first_x_coordinate + controlled_offset*2)
.attr("y", constant_y_coordinate)
.attr("text-anchor","middle");
However, if you have dynamically placed axis that rely on the data, you may want to place the axis info using a function that holds the y coordinate constant while determining the x coordinate based on a fixed "offset" (i.e. data driven axis placement). For example...
svg.append("text")
.attr("class",function(d, i) {return "Axis_" + i; })
.text(function(d,i) {return i; })
.attr("x", function(d, i) { return (x_root_coordinate + x_offset_value*i); })
.attr("y", constant_y_coordinate)
.attr("text-anchor","middle");
I hope this helps.
Frank