Below is a fiddle I have created using a basic D3 pie chart. I am new to D3 and not sure how to do a couple of things. First I would like to correct the labels. As you can see, the 'Correct' label is flying off the edge of the graph currently. But I am not sure how to fix this?
Second, I would like to add a black line around the graph and between the data slices to give the green and red contrast. If you have any ideas of how to do either, I would greatly appreciate it. Thanks!
https://jsfiddle.net/01qew1jk/
JS:
let incorrect = this.resLength - this.points;
let correct = this.points;
let data = [{
'name': 'Correct',
'points': correct
},
{
'name': 'Incorrect',
'points': incorrect
}];
let width = 400, height = 400, radius = Math.min(width, height)/2;
let color = d3.scaleOrdinal().range(['#15B61F', '#DA1821']);
let pie = d3.pie().value(function(d){
return d.points;
})(data);
let arc = d3.arc().outerRadius(radius - 10).innerRadius(0);
let labelArc = d3.arc().outerRadius(radius - 40).innerRadius(radius - 40);
let svg = d3.select('#pie').append('svg').style('display', 'block').style('margin', '0 auto').attr('width', width).attr('height', height).append('g').attr('transform', 'translate(' + width/2 + ',' + height/2 + ')').attr('class', 'float-center');
let g = svg.selectAll('arc').data(pie).enter().append('g').attr('class', 'arc');
g.append('path').attr('d', arc).style('fill', function(d){
return color(d.data.name)
})
g.append('text').attr('transform', function(d) {
return 'translate(' + labelArc.centroid(d ) + ')';
}).text(function(d) {
return d.data.name;
}).style('fill', '#FFF')
For positioning the texts, don't create a new arc generator with different outer and inner radii. Just use the same arc generator you used for the paths:
g.append('text').attr("text-anchor", "middle")
.attr('transform', function(d) {
return 'translate(' + arc.centroid(d) + ')';
//same generator ------^
})
.text(function(d) {
return d.data.name;
})
.style('fill', '#FFF')
To add that "black line", just set the path stroke:
.style("stroke", "black");
Here is your code with those changes:
let incorrect = 3
let correct = 2
let data = [{
'name': 'Correct',
'points': correct
}, {
'name': 'Incorrect',
'points': incorrect
}];
let width = 400,
height = 400,
radius = Math.min(width, height) / 2;
let color = d3.scaleOrdinal().range(['#15B61F', '#DA1821']);
let pie = d3.pie().value(function(d) {
return d.points;
})(data);
let arc = d3.arc().outerRadius(radius - 10).innerRadius(0);
let svg = d3.select('body').append('svg').style('display', 'block').style('margin', '0 auto').attr('width', width).attr('height', height).append('g').attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')').attr('class', 'float-center');
let g = svg.selectAll('arc').data(pie).enter().append('g').attr('class', 'arc');
g.append('path').attr('d', arc).style('fill', function(d) {
return color(d.data.name)
}).style("stroke", "black")
g.append('text').attr("text-anchor", "middle")
.attr('transform', function(d) {
return 'translate(' + arc.centroid(d) + ')';
}).text(function(d) {
return d.data.name;
}).style('fill', '#FFF')
<script src="https://d3js.org/d3.v4.min.js"></script>
Related
I want to create a visual whereby a swarm contains one big circle and a bunch of satellite circles clinging around it. For a simple demonstration, I have prepared a small version of the data set; each item in the array should have one big circle and then however many smaller circles clinging to it:
var data = [
{'wfoe':'wfoe1','products':d3.range(20)},
{'wfoe':'wfoe2','products':d3.range(40)},
{'wfoe':'wfoe3','products':d3.range(10)}
];
Here is a snippet of my progress:
var margins = {
top: 100,
bottom: 300,
left: 100,
right: 100
};
var height = 250;
var width = 900;
var totalWidth = width + margins.left + margins.right;
var totalHeight = height + margins.top + margins.bottom;
var svg = d3.select('body')
.append('svg')
.attr('width', totalWidth)
.attr('height', totalHeight);
var graphGroup = svg.append('g')
.attr('transform', "translate(" + margins.left + "," + margins.top + ")");
var data = [
{'wfoe':'wfoe1','products':d3.range(20)},
{'wfoe':'wfoe2','products':d3.range(40)},
{'wfoe':'wfoe3','products':d3.range(10)}
];
var columns = 4;
var spacing = 250;
var vSpacing = 250;
var fmcG = graphGroup.selectAll('.fmc')
.data(data)
.enter()
.append('g')
.attr('class', 'fmc')
.attr('id', (d, i) => 'fmc' + i)
.attr('transform', (d, k) => {
var horSpace = (k % columns) * spacing;
var vertSpace = ~~((k / columns)) * vSpacing;
return "translate(" + horSpace + "," + vertSpace + ")";
});
var xScale = d3.scalePoint()
.range([0, width])
.domain([0, 100]);
var rScale = d3.scaleThreshold()
.range([50,5])
.domain([0,1]);
data.forEach(function(d, i) {
d.x = (i % columns) * spacing;
d.y = ~~((i / columns)) * vSpacing;
});
var simulation = d3.forceSimulation(data)
.force("x", d3.forceX(function(d,i) {
return (i % columns) * spacing;
}).strength(0.1))
.force("y", d3.forceY(function(d,i) {
return ~~((i / columns)) * vSpacing;
}).strength(0.01))
.force("collide", d3.forceCollide(function(d,i) { return rScale(i)}))
.stop();
simulation.tick(75);
fmcG.selectAll(null)
.data(data)
.enter()
.append("circle")
.attr("r", function(d,i) {
return rScale(i)
})
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.style('fill',"#003366");
<script src="https://d3js.org/d3.v5.min.js"></script>
I want to quickly point out that the big circle doesn't represent any data point (they are just going to house a name / logo). I just thought that including it in the simulation data would be the easiest way to introduce the needed force logic for the swarm circles. I thought that an elegant solution would be to use a threshold scale and let the first (i=0) datum always be the biggest circle. Here is what I mean:
var rScale = d3.scaleThreshold()
.range([0, 1])
.domain([50, 5]);
fmcG.selectAll(null)
.data(data)
.enter()
.append("circle")
.attr("r", function(d,i) {
return rScale(i)
})
.attr("cx", function(d) {
return d.x;
})
.attr("cy", function(d) {
return d.y;
})
.style('fill',"#003366");
The result I mentioned above (three big circles with little circles all around them) was not achieved, and in fact very few circles were appended and the variable radius component didn't seem to be working as I thought it would. (also no errors displayed in the log).
Question
How can I iteratively create swarms that start with one big circle and append subsequent smaller circles around the initial big circle, as applicable to the sample data set?
You could use a force simulation, like below, only this gives non-deterministic results. However, it's really good when you want to gradually add more nodes. In the below solution, I gave all related nodes a link to the center node, but didn't draw it. This made it possible for linked nodes to attract heavily.
On the other hand, you could also use a bubble chart if you want D3 to find the optimal packing solution for you, without the force working on them. Only downside is you'd have to call the packing function with all nodes every time, and the other nodes might shift because of the new one.
var margins = {
top: 100,
bottom: 300,
left: 100,
right: 100
};
var height = 250;
var width = 900;
var totalWidth = width + margins.left + margins.right;
var totalHeight = height + margins.top + margins.bottom;
var svg = d3.select('body')
.append('svg')
.attr('width', totalWidth)
.attr('height', totalHeight);
var graphGroup = svg.append('g')
.attr('transform', "translate(" + margins.left + "," + margins.top + ")");
var data = [{
'wfoe': 'wfoe1',
'products': d3.range(20).map(function(v) {
return v.toString() + '_wfoe1';
})
},
{
'wfoe': 'wfoe2',
'products': d3.range(40).map(function(v) {
return v.toString() + '_wfoe2';
})
},
{
'wfoe': 'wfoe3',
'products': d3.range(10).map(function(v) {
return v.toString() + '_wfoe3';
})
}
];
var columns = 4;
var spacing = 250;
var vSpacing = 250;
function dataToNodesAndLinks(d) {
// Create one giant array of points and
// one link between each wfoe and each product
var nodes = [{
id: d.wfoe,
center: true
}];
var links = [];
d.products.forEach(function(p) {
nodes.push({
id: p,
center: false
});
links.push({
source: d.wfoe,
target: p
});
});
return {
nodes: nodes,
links: links
};
}
var fmcG = graphGroup.selectAll('.fmc')
.data(data.map(function(d, i) {
return dataToNodesAndLinks(d, i);
}))
.enter()
.append('g')
.attr('class', 'fmc')
.attr('id', (d, i) => 'fmc' + i)
.attr('transform', (d, k) => {
var horSpace = (k % columns) * spacing;
var vertSpace = ~~((k / columns)) * vSpacing;
return "translate(" + horSpace + "," + vertSpace + ")";
});
var xScale = d3.scalePoint()
.range([0, width])
.domain([0, 100]);
var rScale = d3.scaleThreshold()
.range([50, 5])
.domain([0, 1]);
fmcG.selectAll("circle")
.data(function(d) {
return d.nodes;
})
.enter()
.append("circle")
.attr("id", function(d) {
return d.id;
})
.attr("r", function(d, i) {
return d.center ? rScale(i) * 5 : rScale(i);
})
.style('fill', function(d) { return d.center ? "darkred" : "#003366"; })
fmcG
.each(function(d, i) {
d3.forceSimulation(d.nodes)
.force("collision", d3.forceCollide(function(d) {
return d.center ? rScale(i) * 5 : rScale(i);
}))
.force("center", d3.forceCenter(0, 0))
.force("link", d3
.forceLink(d.links)
.id(function(d) {
return d.id;
})
.distance(0)
.strength(2))
.on('tick', ticked);
});
function ticked() {
fmcG.selectAll("circle")
.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
}
<script src="https://d3js.org/d3.v5.js"></script>
I'm having an issue with a D3 pie chart where labels are cutoff when they appear. Here's a pic:
I'm new to D3, and am not sure exactly where a fix should be. The logic for making the pie chart is 400 lines, so I made a pastebin: https://pastebin.com/32CxpeDM
Maybe the issue is in this function?
function showDetails(layer, data) {
active.inner = !active.inner
active.outer = false
let lines = guideContainer.selectAll('polyline.guide-line-inner')
.data(pie(data.inner))
let text = guideContainer.selectAll('.inner-text')
.data(pie(data.inner))
if (active.inner) {
// LINES
lines.enter()
.append('polyline')
.attr('points', calcPoints)
.attr('class', 'guide-line-inner')
.style('opacity', 0)
.transition().duration(300)
.style('opacity', d => { return d.data.value <= 0 ? 0 : 1 })
lines.attr('points', calcPoints).attr('class', 'guide-line-inner')
// TEXT
text.enter()
.append('text')
.html(labelText)
.attr('class', 'inner-text label label-circle')
.attr('transform', labelTransform)
.attr('dy', '1.1em')
.attr('x', d => { return (midAngle(d) < Math.PI ? 15 : -15) })
.style('text-anchor', d => { return (midAngle(d)) < Math.PI ? 'start' : 'end' })
.style('opacity', 0)
.call(wrap, 300)
.on('click', d => { vm.$emit('details', d) })
.transition().duration(300)
.style('opacity', d => { return d.data.value <= 0 ? 0 : 1 })
} else {
lines.transition().duration(300)
.style('opacity', 0)
.remove()
text.transition().duration(300)
.style('opacity', 0)
.remove()
}
guideContainer.selectAll('polyline.guide-line-outer').transition().duration(300)
.style('opacity', 0)
.remove()
guideContainer.selectAll('.outer-text').transition().duration(300)
.style('opacity', 0)
.remove()
}
Like I said, I don't know D3 so I'm not sure what my options are for fixing this. Make the chart smaller, fix some problem with its div container, send it to the front, or edit the above code. Ideally this would be a clean fix and not a hack, which is what I've been trying.
What the easiest and cleanest fix for this problem?
Thanks!
It looks like your labels are getting transformed past the edge of your SVG boundary.
I would try to translate the label elements farther left in this function:
function labelTransform (d) {
var pos = guideArc.centroid(d)
pos[0] = (radius + 100) * (midAngle(d) < Math.PI ? 1 : -1)
return 'translate(' + pos + ')'
}
You'll have to chase down where the label line is being generated and shorten that as well.
You might also try braking the label text into more lines in this function:
function labelText (d) {
if ((radius + 100) * (midAngle(d) < Math.PI ? 1 : 0)) {
return '<tspan>' + d.data.display_name + ' </tspan><tspan x="15">' + d3.format('($,.0f')(d.data.value) + '</tspan>'
} else {
return '<tspan>' + d.data.display_name + ' </tspan><tspan x="-15" text-anchor="end">' + d3.format('($,.0f')(d.data.value) + '</tspan>'
}
}
One approach that would conserve space would be to use d3 tooltips instead of fixed-position labels as in this fiddle (created by another jsfiddle user, I just added the margin)
Javascript:
//Width/height
var w = 300;
var h = 300;
var dataset = [5, 10, 20, 45, 6, 25];
var outerRadius = w / 2;
var innerRadius = w / 3;
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.layout.pie();
var color = d3.scale.category10();
//Create SVG element
var svg = d3.select("#vis")
.append("svg")
.attr("width", w)
.attr("height", h);
//Set up groups
var arcs = svg.selectAll("g.arc")
.data(pie(dataset))
.enter()
.append("g")
.attr("class", "arc")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
//Draw arc paths
arcs.append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
//Labels
arcs.append("text")
.attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("text-anchor", "middle")
.text(function(d) {
return d.value;
});
//
var tip = d3.tip()
.attr("class", "d3-tip")
.html(function(d, i) {
return d.value
})
svg.call(tip)
arcs
.on("mouseover", tip.show)
.on("mouseout", tip.hide)
This uses a d3 tip library by Justin Palmer, that can be found on Github.
Also, you could consider making the circle smaller?
Hope this helps
Let's consider a horizontal bar chart as shown in the attached photo. I need to show the duration of each segment along with the x-axis. I am able to show the tick values using d3.svg.axis().tickValues(vals).
But I need to show the duration in between two ticks. Can anyone help me to achieve this using d3?
Thanks in advance.
Here is my solution. I'm using D3 version 3 (because you wrote d3.svg.axis() in your question) and a linear scale, just to show you the principle. You can easily change it to a time scale.
Given this data:
var data = [0, 10, 40, 45, 85, 100];
We're gonna plot the differences between the ticks, i.e.: 10, 30, 5, 40 and 15.
The first step is setting the scale:
var scale = d3.scale.linear()
.domain(d3.extent(data))
.range([margin, w - margin]);
Then, in the axis generator, we set the ticks to match the data with:
.tickValues(data)
And we calculate the correct numbers with:
.tickFormat(function(d,i){
if(i>0){
return data[i] - data[i-1];
} else { return ""};
});
The last step is translating the text to the middle position:
var ticks = d3.selectAll(".tick text").each(function(d, i) {
d3.select(this).attr("transform", function() {
if (i > 0) {
return "translate(" + (-scale(data[i] - data[i - 1]) / 2 + margin/2) + ",0)";
}
})
})
Check the demo:
var w = 500,
h = 100;
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
var data = [0, 10, 40, 45, 85, 100];
var margin = 20;
var scale = d3.scale.linear()
.domain(d3.extent(data))
.range([margin, w - margin]);
var colors = d3.scale.category10();
var rects = svg.selectAll(".rects")
.data(data)
.enter()
.append("rect");
rects.attr("y", 10)
.attr("height", 35)
.attr("fill", (d,i)=> colors(i))
.attr("x", d=>scale(d))
.attr("width", (d,i)=> {
return scale(data[i+1] - data[i]) - margin
});
var axis = d3.svg.axis()
.scale(scale)
.orient("bottom")
.tickValues(data)
.tickFormat(function(d, i) {
if (i > 0) {
return data[i] - data[i - 1];
} else {
return ""
};
});
var gX = svg.append("g")
.attr("transform", "translate(0,50)")
.attr("class", "axis")
.call(axis);
var ticks = d3.selectAll(".tick text").each(function(d, i) {
d3.select(this).attr("transform", function() {
if (i > 0) {
return "translate(" + (-scale(data[i] - data[i - 1]) / 2 + margin / 2) + ",0)";
}
})
})
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I’d like to select a node in a callback without using d3.select(this).
I have some code that draws a pie…
function drawPie(options) {
options || (options = {});
var data = options.data || [],
element = options.element,
radius = options.radius || 100,
xOffset = Math.floor(parseInt(d3.select(element).style('width'), 10) / 2),
yOffset = radius + 20;
var canvas = d3.select(element)
.append("svg:svg")
.data([data])
.attr("width", options.width)
.attr("height", options.height)
.append("svg:g")
.attr("transform", "translate(" + xOffset + "," + yOffset + ")");
var arc = d3.svg.arc()
.outerRadius(radius);
var pie = d3.layout.pie()
.value(function(data) {
return data.percentageOfSavingsGoalValuation;
});
var arcs = canvas.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
arcs.append("svg:path")
.on("mouseover", divergeSlice);
You’ll notice at the end I have a call to divergeSlice(). That looks like this:
function divergeSlice(datum, index) {
var angle = (datum.endAngle + datum.startAngle) / 2,
x = Math.sin(angle) * 10,
y = -Math.cos(angle) * 10;
d3.select(this)
.transition()
.attr("transform", "translate(" + x + ", " + y + ")");
}
This works, but I’d like to accomplish this without using this as I mentioned earlier. When I log the datum object, I get something like the following:
{
data: {
uniqueID: "XX00X0XXXX00"
name: "Name of value"
percentageOfValuation: 0.4
totalNetAssetValue: 0
}
endAngle: 5.026548245743669
innerRadius: 80
outerRadius: 120
startAngle: 2.5132741228718345
value: 0.4
}
How could I use d3.select() to find a path that holds datum.data.uniqueID that is equal to "XX00X0XXXX00"?
You can't do this directly with .select() as that uses DOM selectors. What you can do is select all the candidates and then filter:
d3.selectAll("g")
.filter(function(d) { return d.data.uniqueID === myDatum.data.uniqueID; });
However, it would be much easier to simply assign this ID as an ID to the DOM element and then select based on that:
var arcs = canvas.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("id", function(d) { return d.data.uniqueID; })
.attr("class", "slice");
d3.select("#" + myDatum.data.uniqueID);
I'm drawing a pie chart using D3.js with a quite simple script. The problem is that when slices are small, their labels overlap.
What options do I have to prevent them from overlapping? Does D3.js have built-in mechanisms I could exploit?
Demo: http://jsfiddle.net/roxeteer/JTuej/
var container = d3.select("#piechart");
var data = [
{ name: "Group 1", value: 1500 },
{ name: "Group 2", value: 500 },
{ name: "Group 3", value: 100 },
{ name: "Group 4", value: 50 },
{ name: "Group 5", value: 20 }
];
var width = 500;
var height = 500;
var radius = 150;
var textOffset = 14;
var color = d3.scale.category20();
var svg = container.append("svg:svg")
.attr("width", width)
.attr("height", height);
var pie = d3.layout.pie().value(function(d) {
return d.value;
});
var arc = d3.svg.arc()
.outerRadius(function(d) { return radius; });
var arc_group = svg.append("svg:g")
.attr("class", "arc")
.attr("transform", "translate(" + (width/2) + "," + (height/2) + ")");
var label_group = svg.append("svg:g")
.attr("class", "arc")
.attr("transform", "translate(" + (width/2) + "," + (height/2) + ")");
var pieData = pie(data);
var paths = arc_group.selectAll("path")
.data(pieData)
.enter()
.append("svg:path")
.attr("stroke", "white")
.attr("stroke-width", 0.5)
.attr("fill", function(d, i) { return color(i); })
.attr("d", function(d) {
return arc({startAngle: d.startAngle, endAngle: d.endAngle});
});
var labels = label_group.selectAll("path")
.data(pieData)
.enter()
.append("svg:text")
.attr("transform", function(d) {
return "translate(" + Math.cos(((d.startAngle + d.endAngle - Math.PI) / 2)) * (radius + textOffset) + "," + Math.sin((d.startAngle + d.endAngle - Math.PI) / 2) * (radius + textOffset) + ")";
})
.attr("text-anchor", function(d){
if ((d.startAngle +d.endAngle) / 2 < Math.PI) {
return "beginning";
} else {
return "end";
}
})
.text(function(d) {
return d.data.name;
});
D3 doesn't offer anything built-in that does this, but you can do it by, after having added the labels, iterating over them and checking if they overlap. If they do, move one of them.
var prev;
labels.each(function(d, i) {
if(i > 0) {
var thisbb = this.getBoundingClientRect(),
prevbb = prev.getBoundingClientRect();
// move if they overlap
if(!(thisbb.right < prevbb.left ||
thisbb.left > prevbb.right ||
thisbb.bottom < prevbb.top ||
thisbb.top > prevbb.bottom)) {
var ctx = thisbb.left + (thisbb.right - thisbb.left)/2,
cty = thisbb.top + (thisbb.bottom - thisbb.top)/2,
cpx = prevbb.left + (prevbb.right - prevbb.left)/2,
cpy = prevbb.top + (prevbb.bottom - prevbb.top)/2,
off = Math.sqrt(Math.pow(ctx - cpx, 2) + Math.pow(cty - cpy, 2))/2;
d3.select(this).attr("transform",
"translate(" + Math.cos(((d.startAngle + d.endAngle - Math.PI) / 2)) *
(radius + textOffset + off) + "," +
Math.sin((d.startAngle + d.endAngle - Math.PI) / 2) *
(radius + textOffset + off) + ")");
}
}
prev = this;
});
This checks, for each label, if it overlaps with the previous label. If this is the case, a radius offset is computed (off). This offset is determined by half the distance between the centers of the text boxes (this is just a heuristic, there's no specific reason for it to be this) and added to the radius + text offset when recomputing the position of the label as originally.
The maths is a bit involved because everything needs to be checked in two dimensions, but it's farily straightforward. The net result is that if a label overlaps a previous label, it is pushed further out. Complete example here.
#LarsKotthoff
Finally I have solved the problem. I have used stack approach to display the labels. I made a virtual stack on both left and right side. Based the angle of the slice, I allocated the stack-row. If stack row is already filled then I find the nearest empty row on both top and bottom of desired row. If no row found then the value (on the current side) with least share angle is removed from the stack and labels are adjust accordingly.
See the working example here:
http://manicharts.com/#/demosheet/3d-donut-chart-smart-labels
The actual problem here is one of label clutter.
So, you could try not displaying labels for very narrow arcs:
.text(function(d) {
if(d.endAngle - d.startAngle<4*Math.PI/180){return ""}
return d.data.key; });
This is not as elegant as the alternate solution, or codesnooker's resolution to that issue, but might help reduce the number of labels for those who have too many. If you need labels to be able to be shown, a mouseover might do the trick.
For small angles(less than 5% of the Pie Chart), I have changed the centroid value for the respective labels. I have used this code:
arcs.append("text")
.attr("transform", function(d,i) {
var centroid_value = arc.centroid(d);
var pieValue = ((d.endAngle - d.startAngle)*100)/(2*Math.PI);
var accuratePieValue = pieValue.toFixed(0);
if(accuratePieValue <= 5){
var pieLableArc = d3.svg.arc().innerRadius(i*20).outerRadius(outer_radius + i*20);
centroid_value = pieLableArc.centroid(d);
}
return "translate(" + centroid_value + ")";
})
.text(function(d, i) { ..... });