semicircle bar graphs with extended edges using d3.js - d3.js

I'm trying to draw a d3 chart with extended edges like in the image, "this is the link to the design"
I was able to achieve a semi circle in the same fashion, but I'm a little confused how to do the extended edge, this is the code for what I have done so far, link to codepen
JS:
var width = 300,
height = 300;
var twoPi = Math.PI; // Full circle
var formatPercent = d3.format(".0%");
const color = [
"#F9C969",
"#FB8798",
"#51D6D8",
"#B192FD",
"#509FFD",
"#5B65B7"
];
console.log(d3.schemeCategory10);
var data = [
{ count: 1000 },
{ count: 800 },
{ count: 800 },
{ count: 700 },
{ count: 900 },
{ count: 600 }
];
var percent = d3.max(data, function (d) {
return +d.count / 10;
});
var max = d3.max(data, function (d) {
return +d.count;
});
var baseRad = 0.25,
cgap = 12,
maxVal = max + percent;
var cx1 = width / 2.5;
var cy1 = height / 2.5;
var cl = "c0";
var ind = 0;
var rad;
var rad2;
rad = baseRad;
rad2 = baseRad;
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 10 + "," + height / 10 + ")");
var svg2 = d3
.select("svg")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 10 + "," + height / 10 + ")");
svg2
.selectAll("path")
.data(data)
.enter()
.append("path")
// .each(drawBackArc)
.each(drawArc)
.style("fill", function (d, i) {
return color[i % 6];
});
svg
.selectAll("path")
.data(data)
.enter()
.append("path")
// .each(drawBackArc)
.each(drawBackArc)
.style("fill", "#F1F1F1");
// .attr("ax", "-100px")
// .attr("ay", "-100px");
function drawArc(d, i) {
console.log(d, i);
var ratio = d.count / maxVal;
var arc = d3.svg
.arc()
.startAngle(3.14159)
// .(true)
.endAngle(6.28319 * ratio)
.innerRadius(72 + cgap * rad)
.outerRadius(80 + cgap * rad);
d3.select(this)
.attr("transform", "translate(" + cx1 + "," + cy1 + ")")
.attr("d", arc)
.style("fill", function (d, i) {
return color[i % 6];
});
rad++;
}
function drawBackArc(d, i) {
var ratio = d.count / maxVal;
var arc = d3.svg
.arc()
.startAngle(twoPi)
// .(true)
.endAngle(twoPi * 2)
.innerRadius(72 + cgap * rad2)
.outerRadius(80 + cgap * rad2);
d3.select(this)
.attr("transform", "translate(" + cx1 + "," + cy1 + ")")
.attr("d", arc)
.style("fill", "#F1F1F1");
rad2++;
}
HTML:
<script src="https://d3js.org/d3.v3.min.js"></script>
<body></body>
CSS:
body{background-color: #fff;margin: 1.5rem 6rem}
I have seen tutorial explaining how to draw different shapes in d3.js and I can think of drawing a rectangle shape at one end to achieve the design, but even then the issue is how to get the data in both the separate shapes, is it possible in d3? if not please suggest any other possible ways if any.
Thanks

Since you know your center point, you added 2 translations (30,30) and (120,120), so your center point is 150,150
Now you can get the end points of all the arcs, x value be same as centerpoint and y after adjusting radius.
Added below changes to your code Please adjust your graph for length and width of the line. Also add the length of the line to the lenght of arc to get correct percantage and overlap with filled line same as below with desired length if percentage increase the length of an arc
var centerPoint = [150, 150] //added for translation
var radius = 72 + cgap * rad2;
gLines.append("line")
.attr("x1", centerPoint[0])
.attr("x2", centerPoint[0] + 140) // Add length of the bar
.attr("y1", centerPoint[0] - radius + 16)
.attr("y2", centerPoint[0] - radius + 16) // This will adjust line width and inner and outer radius
.style("stroke", "#F2F2F2")
.style("stroke-width", "8");
var width = 300,
height = 300;
var twoPi = Math.PI; // Full circle
var formatPercent = d3.format(".0%");
const color = [
"#F9C969",
"#FB8798",
"#51D6D8",
"#B192FD",
"#509FFD",
"#5B65B7"
];
console.log(d3.schemeCategory10);
var data = [{
count: 500,
color: "#F9C969"
},
{
count: 800,
color: "#FB8798"
},
{
count: 800,
color: "#51D6D8"
},
{
count: 700,
color: "#B192FD"
},
{
count: 900,
color: "#509FFD"
},
{
count: 600,
color: "#5B65B7"
}
];
var percent = d3.max(data, function(d) {
return +d.count / 10;
});
var max = d3.max(data, function(d) {
return +d.count;
});
var baseRad = 0.25,
cgap = 12,
maxVal = max + percent;
var cx1 = width / 2.5;
var cy1 = height / 2.5;
var cl = "c0";
var ind = 0;
var rad;
var rad2;
rad = baseRad;
rad2 = baseRad;
var svg = d3
.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 10 + "," + height / 10 + ")");
var svg2 = d3
.select("svg")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 10 + "," + height / 10 + ")");
var gLines = d3.select("svg").append("g");
svg2
.selectAll("path")
.data(data)
.enter()
.append("path")
// .each(drawBackArc)
.each(drawArc)
.style("fill", function(d, i) {
return color[i % 6];
});
svg
.selectAll("path")
.data(data)
.enter()
.append("path")
// .each(drawBackArc)
.each(drawBackArc)
.style("fill", "#F1F1F1");
// .attr("ax", "-100px")
// .attr("ay", "-100px");
function drawArc(d, i) {
console.log(d, i);
var ratio = (d.count * 2) / maxVal;
console.log(ratio);
var arc = d3.svg
.arc()
.startAngle(twoPi)
// .(true)
.endAngle(twoPi * ratio)
.innerRadius(72 + cgap * rad)
.outerRadius(80 + cgap * rad);
d3.select(this)
.attr("transform", "translate(" + cx1 + "," + cy1 + ")")
.attr("d", arc)
.style("fill", function(d, i) {
return color[i % 6];
});
rad++;
}
function drawBackArc(d, i) {
var ratio = d.count / maxVal;
var arc = d3.svg
.arc()
.startAngle(twoPi)
// .(true)
.endAngle(twoPi * 2)
.innerRadius(72 + cgap * rad2 - 20)
.outerRadius(80 + cgap * rad2 - 20);
d3.select(this)
.attr("transform", "translate(" + cx1 + "," + cy1 + ")")
.attr("d", arc)
.style("fill", "#F1F1F1");
var centerPoint = [150, 150] //added for translation
var radius = 72 + cgap * rad2;
gLines.append("line")
.attr("x1", centerPoint[0])
.attr("x2", centerPoint[0] + 140) // Add Width of the
.attr("y1", centerPoint[0] - radius + 16)
.attr("y2", centerPoint[0] - radius + 16)
.style("stroke", "#F2F2F2")
.style("stroke-width", "8");
rad2++;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<body></body>

Related

d3.js geoGraticule doesn't follow the sphere shape

I am trying to add standard geoGraticule lines to my globe, which spins and has ripple effects. I've gone wrong somewhere but can't get to the bottom of it: live demo
The meridian lines seem to create a sort of diamond shape, rather than curving around the whole sphere.
How can I change my code so the graticule is spherical?
// margin calculations
const margin = {top: 50, right: 0, bottom: 50, left: 0};
const width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
const config = {
speed: 0.005,
verticalTilt: -30,
horizontalTilt: 0
}
// add an SVG to the body and a g group
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var g = svg.append("g");
// draw a globe I guess
d3.json("https://unpkg.com/world-atlas#1.1.4/world/110m.json", (error, world) => {
// draw the land using TOPOJSON package
var land = topojson.feature(world, world.objects.land);
// d3 3d globe projection
var projection = d3.geoOrthographic()
.fitSize([width, height], land)
.clipAngle(90)
.precision(0)
.scale(200);
// create projection of earth sphere
var path = d3.geoPath()
.projection(projection);
// load the ripple circle
var geoCircle = d3.geoCircle();
// load the meridian lines
var graticule = d3.geoGraticule();
// draw a grey circle to look like water
var ocean = g.append("circle")
.attr("class", "ocean")
.attr("cx", width / 2)
.attr("cy", height / 2)
.attr("r", height / 2);
// draw countries
var earth = g.append("path")
.datum(land)
.attr("d", path);
// draw graticules
var lines = g.append("path")
.datum(graticule)
.attr("class", "graticule")
.attr("d", path)
.style("fill-opacity", 0)
.style("stroke", "#ccc")
.style("stroke-opacity", 0.7);
// list of locations - reverse the lat / long numbers!
var locale = [
[37.5999, 14.0153],
[10.1278, 50.5074],
[0.1278, 51.5074],
[25.653906, 4.453784],
[0, -10],
[151.2012775, -33.8844644]
];
// draw the circles
function drawMarkers() {
for (var i = 0; i < locale.length; i++) {
// console.log("location " + (i+1) + ": " + locale[i]);
center = locale[i];
var circ = g.append("path")
.datum({endAngle: 0})
.attr("class", "geoCircle")
.attr("fill", "#000")
.attr("fill-opacity", 1)
.attr("d", d => path(geoCircle.center(center).radius(1)()));
}
}
// draw the ripples
setInterval(() => {
for (var i = 0; i < locale.length; i++) {
center = locale[i];
var circ = g.append("path")
.datum({endAngle: 0})
.attr("class", "ripple ripple" + i)
.attr("fill", "#000")
.attr("fill-opacity", 0.2)
.attr("opacity", 1)
.attr("d", d => path(geoCircle.center(center).radius(2)()))
.transition()
.delay(0)
.duration(2800)
.ease(d3.easeLinear)
.attr("opacity", 0)
.attrTween("d", geoCircleTween(12, center))
.remove();
function geoCircleTween(newAngle, loca) {
return function(d) {
var interpolate = d3.interpolate(d.endAngle, newAngle);
return function(t) {
d.endAngle = interpolate(t);
return path(geoCircle.center(loca).radius(d.endAngle)());
};
};
}
}
}, 500)
function enableRotation() {
d3.timer(function (elapsed) {
projection.rotate([config.speed * elapsed - 120, config.verticalTilt, config.horizontalTilt]);
svg.selectAll("path").attr("d", path);
drawMarkers();
});
}
enableRotation();
});

How to add image at the end of Arc

I am using d3 js i have to show image at the end of the arc how can i achieve that below is my example
var total_codes = 8;
var remaining_codes = 4;
var issued = total_codes - remaining_codes;
var coloursArray = ["#128ED2", "#dadada"];
var dataset = {
privileges: [issued, remaining_codes]
};
var width = 160,
height = 160,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(coloursArray);
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 30)
.outerRadius(radius);
var svg = d3.select("#donut").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(dataset.privileges))
.enter().append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
path.transition().duration(750);
var point = path.node().getPointAtLength(path.node().getTotalLength() / 2);
svg.append("image")
.attr("cx", point.x)
.attr("cy", point.y)
.attr({
"xlink:href": "http://run.plnkr.co/preview/ckf41wu0g00082c6g6bzer2cc/images/pacman_active_icon.png", //nothing visible
width: 35,
height: 36
});
svg.append("text")
.attr("dy", ".0em")
.style("text-anchor", "middle")
.attr("class", "inside")
.html(function() {
return "<tspan x='0' dy='0em'>External</tspan><tspan x='0' dy='1.2em'>Privileges</tspan>";
}); // Add your code here
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="donut"></div>
It's a bit tedious, but the following works.
You take the first element of pieData, which denotes the blue arc. Then calculate the offset to put the pacman in the right position, using trigonometry. Finally, first translate it so it rotates around its centre, then rotate it the required amount.
I placed it at radius - 15 from the centre, because that is the middle of the 30 pixel wide arc.
var total_codes = 8;
var remaining_codes = 5;
var issued = total_codes - remaining_codes;
var coloursArray = ["#128ED2", "#dadada"];
var dataset = {
privileges: [issued, remaining_codes]
};
var width = 160,
height = 160,
radius = Math.min(width, height) / 2,
iconSize = 48;
var color = d3.scale.ordinal()
.range(coloursArray);
var pie = d3.layout.pie()
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 30)
.outerRadius(radius);
var svg = d3.select("#donut").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var pieData = pie(dataset.privileges);
var path = svg.selectAll("path")
.data(pieData)
.enter().append("path")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc);
path.transition().duration(750);
svg
.append('g')
.attr('class', 'pacmancontainer')
.style('transform', function() {
// the radius of the center of the arc, also the hypothenuse of a triangle
var meanRadius = radius - 15;
var angleRadians = pieData[0].endAngle - Math.PI / 2;
var xOffset = Math.cos(angleRadians) * meanRadius;
var yOffset = Math.sin(angleRadians) * meanRadius;
return " translate(" + xOffset + "px, " + yOffset + "px)";
})
.append("image")
.attr({
"xlink:href": "http://run.plnkr.co/preview/ckf41wu0g00082c6g6bzer2cc/images/pacman_active_icon.png", //nothing visible
width: iconSize,
height: iconSize
})
// Make sure the Pacman rotates around its center
.style('transform-origin', (iconSize / 2) + 'px ' + (iconSize / 2) + 'px')
.style('transform', function() {
var angleDegrees = pieData[0].endAngle / (2 * Math.PI) * 360;
return "translate(-" + (iconSize / 2) + "px, -" + (iconSize / 2) + "px) rotate(" + angleDegrees + "deg)";
});
svg.append("text")
.attr("dy", ".0em")
.style("text-anchor", "middle")
.attr("class", "inside")
.html(function() {
return "<tspan x='0' dy='0em'>External</tspan><tspan x='0' dy='1.2em'>Privileges</tspan>";
}); // Add your code here
<script src="https://d3js.org/d3.v3.min.js"></script>
<div id="donut"></div>

D3JS: Unable to place a group of text elements over several rectangles

I'm trying to create a set of text elements and place them above various rect elements so that it looks as if they were inside. the thing is that I haven't been able to accomplish this simple task.
The text elements I need inside the column of rect's are the elements of the array: var dataDnt4 = [42,31,16,4,3,2,1];
I'll leave a running snippet so that you can my progress so far.
Your help is very appreciated. thanks
var icon2 = '<g><path class="st0" d="M23.1,34.9c6.9,0,12.5-5.6,12.5-12.5c0-6.9-5.6-12.5-12.5-12.5c-6.9,0-12.5,5.6-12.5,12.5 C10.6,29.3,16.2,34.9,23.1,34.9L23.1,34.9z"/><path class="st0" d="M39.2,54.6c0.2,0,0.4,0,0.7,0c-3.7-3-6-7.5-6-12.6c0-1.2,0.1-2.4,0.4-3.6c-0.1,0-0.3,0-0.4,0H12.4 C5.5,38.5-0.1,44.1-0.1,51v17.9h23.3C24.1,60.8,30.9,54.6,39.2,54.6L39.2,54.6z"/><path class="st0" d="M76.8,34.9c6.9,0,12.5-5.6,12.5-12.5c0-6.9-5.6-12.5-12.5-12.5c-6.9,0-12.5,5.6-12.5,12.5 C64.2,29.3,69.9,34.9,76.8,34.9L76.8,34.9z"/><path class="st0" d="M87.5,38.5H66c-0.1,0-0.3,0-0.4,0c0.3,1.1,0.4,2.3,0.4,3.6c0,5.1-2.4,9.6-6,12.6c0.2,0,0.4,0,0.7,0 c8.3,0,15.1,6.3,16,14.3H100V51C100,44.1,94.4,38.5,87.5,38.5L87.5,38.5z"/><path class="st0" d="M49.9,54.6c6.9,0,12.5-5.6,12.5-12.5c0-6.9-5.6-12.5-12.5-12.5c-6.9,0-12.5,5.6-12.5,12.5 C37.4,49,43,54.6,49.9,54.6L49.9,54.6z"/><path class="st0" d="M60.7,58.1H39.2c-6.9,0-12.5,5.6-12.5,12.5v17.9h46.5V70.7C73.2,63.7,67.6,58.1,60.7,58.1L60.7,58.1z"/></g>'
var dataDnt4 = [42, 31, 16, 4, 3, 2, 1];
var distanciaRect = [25, 50, 75, 100, 125, 150, 175]
var width = 512,
height = 600
radius = (Math.min(width, height) / 2.5) - 60;
var sym = "%"
var legendTextArr = ["alpha", "beta", "Gamma", "vvv", "www", "xxx", "yyy", "zzz"]
var color_rect = ["#00338D", "#BC204B", "#0091DA", "#eaaa00", "#005eb8", "#f68d2e", "#009444", "#470a68"]
var pie = d3.pie()
.value(function(d) {
return d
})(dataDnt4);
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(radius - (radius / 2.4));
var labelArc = d3.arc()
.outerRadius(radius - 35)
.innerRadius(radius - 35);
var svg = d3.select("#chartdiv")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2.4 + ")");
var title = svg.append("text")
.attr("font-weight", "bold")
.attr("class", "title1")
.html("title 1")
.attr("transform", function() {
return "translate(" + (-184) + "," + (-180) + ")"
})
var title = svg.append("text")
.attr("font-weight", "bold")
.attr("class", "title2")
.html("title 2")
.attr("transform", function() {
return "translate(" + (-184) + "," + (-160) + ")"
})
var legendG = svg.append("g")
.attr("class", "legendG")
.attr("transform", function() {
return "translate(" + (-60) + "," + (155) + ")"
})
var legendG = svg.append("g")
.attr("class", "legendG")
.attr("transform", function() {
return "translate(" + (-60) + "," + (155) + ")"
})
var legendText = legendG.selectAll("text")
.data(distanciaRect)
.enter()
.append("text")
.attr("x", -80)
.attr("y", function(d, i) {
return d + 10
})
.data(legendTextArr)
.html(function(d) {
return d
})
var legends = legendG.selectAll(".rect")
.data(distanciaRect)
.enter()
.append("rect")
.attr("x", -120)
.attr("y", function(d, i) {
return d
})
.attr("width", 25)
.attr("height", 17)
.attr("class", "icon1")
.data(color_rect)
.attr("fill", function(d, i) {
return d
})
var g = svg.selectAll("arc")
.data(pie)
.enter().append("g")
.attr("class", "arc");
function easeInverse(ease) {
return function(e) {
var min = 0,
max = 1;
while (max - min > 1e-3) {
var mid = (max + min) * 0.5;
emid = ease(mid);
if (emid > e) {
max = mid;
} else {
min = mid;
}
}
return max;
}
}
var inverseCubic = easeInverse(d3.easeCubic);
var oneOver2Pi = 1.0 / (2 * Math.PI);
var total_msec = 2000;
g.append("path")
.attr("d", arc)
.attr("transform", function() {
return "translate(" + (-16) + "," + (0) + ")"
})
.style("fill", function(d, i) {
return color_rect[i];
})
.transition()
.ease(d3.easeLinear)
.delay(function(d) {
return total_msec * inverseCubic(d.startAngle * oneOver2Pi);
})
.duration(function(d) {
return total_msec * (inverseCubic(d.endAngle * oneOver2Pi) - inverseCubic(d.startAngle * oneOver2Pi));
})
.attrTween("d", arcTween);
function arcTween(d) {
var i = d3.interpolate(inverseCubic(d.startAngle * oneOver2Pi), inverseCubic(d.endAngle * oneOver2Pi));
return function(t) {
d.endAngle = 2 * Math.PI * d3.easeCubic(i(t));
return arc(d);
}
}
svg.append("g")
.attr("class", "icon2")
.html(icon2);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://d3js.org/d3.v5.min.js"></script>
<div id="chartdiv"></div>
There are numerous ways to do this, so here is one possible way. I would group together the three pieces of the legend--the rectangle, the key text, and the text over the rectangle--in a g element and bind dataDnt4 to each item. The rectangle colour and the legend text can be retrieved by position, i.e. the first dataDnt4 item corresponds to color_rect[0] and legendTextArr[0], the second to color_rect[1] and legendTextArr[1], etc.
I've cut out the code that is not relevant to the positioning of the legend items -- you can restore that in your script.
var width = 512,
height = 600,
radius = (Math.min(width, height) / 2.5) - 60;
var sym = "%"
var legendTextArr = ["alpha", "beta", "Gamma", "vvv", "www", "xxx", "yyy", "zzz"]
var dataDnt4 = [42, 31, 16, 4, 3, 2, 1];
var color_rect = ["#00338D", "#BC204B", "#0091DA", "#eaaa00", "#005eb8", "#f68d2e", "#009444", "#470a68"]
var svg = d3.select("#chartdiv")
.append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2.4 + ")");
var title = svg.append("text")
.attr("font-weight", "bold")
.attr("class", "title1")
.html("scroll down!")
.attr("transform", function() {
return "translate(" + -184 + "," + -180 + ")"
})
var legendG = svg.append("g")
.attr("class", "legendG")
.attr("transform", function() {
// this moves the whole legend box
// you can change this to whatever transformation is appropriate for your chart
return "translate(" + -((width / 2)-40) + "," + 120 + ")"
})
// group each legend item in a `g` element
var legendText = legendG.selectAll("g")
.data(dataDnt4)
.enter()
.append('g')
.attr('transform', function(d, i) {
// instead of having a hard-coded list of multiples of 25, you can multiply
// the array index, `i`, by 25 to get the correct position
return 'translate(0,' + (i*25) + ')';
});
legendText.append("rect")
.attr("width", 25)
.attr("height", 17)
.attr("class", "icon1")
.attr("fill", function(d, i) {
return color_rect[i];
})
// the text "in" the rectangle
// use 'text-anchor: middle' and an x offset of 12.5 (rectangle width / 2)
// to centre the labels
// change the `y` attribute to alter the vertical positioning
legendText.append("text")
.attr("x", 12.5)
.attr("y", 13)
.attr('text-anchor', 'middle')
.attr('fill', 'white')
// d is the items in dataDnt4
.text(function(d) {
return d;
})
// legend text items
legendText.append("text")
.attr("x", 40)
.attr("y", 13)
// take legendTextArr item in position i
.text(function(d,i) {
return legendTextArr[i];
})
<script src="https://d3js.org/d3.v5.min.js"></script>
<div id="chartdiv"></div>
You have some errors in your code (e.g. you declare the variables legendG and title twice), and it would probably be helpful for you to run your code through a code linter so you can see the problems that you might not pick up by eye.

move a slice of the pie chart using d3.js

In the code below, a simple pie chart is created, but I am not able to move one slice towards the outer side of the chart when selected.
I want the individual (element) slice to be positioned outer the pie and the rest of the pie chart elements(slices) in its usual position, something like this:
Here is my code:
<!DOCTYPE html>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [35, 20, 45];
var width = 300,
height = 300,
radius = 150;
var arc = d3.arc()
.outerRadius(130);
var arcLabel = d3.arc()
.outerRadius(radius - 30)
.innerRadius(radius - 20);
var pie = d3.pie()
.value(function(d) {
return d;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var emptyPies = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc")
emptyPies.append("path")
.attr("d", arc)
.style("fill", function(d, i) {
return color[i];
})
emptyPies.append("text")
.attr("transform", function(d) {
return "translate(" + arcLabel.centroid(d) + ")";
})
.text(function(d) {
return d.data;
});
</script>
A simple solution is creating a different arc generator:
var arc2 = d3.arc()
.outerRadius(radius)
.innerRadius(60);
And, when setting the "d" attribute, choosing which arc generator to use. For instance, moving the red slice:
emptyPies.append("path")
.attr("d", function(d,i){
return i != 1 ? arc(d) : arc2(d);
})
Here is your code with that change:
<!DOCTYPE html>
<style>
.arc text {
text-anchor: middle;
}
.arc path {
stroke: white;
}
</style>
<body>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var data = [35, 20, 45];
var width = 300,
height = 300,
radius = Math.min(width, height) / 2;
var color = ["brown", "red", "blue"];
var arc = d3.arc()
.outerRadius(radius - 10)
.innerRadius(50);
var arc2 = d3.arc()
.outerRadius(radius)
.innerRadius(60);
var arcLabel = d3.arc()
.outerRadius(radius - 30)
.innerRadius(radius - 20);
var pie = d3.pie()
.value(function(d) {
return d;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var emptyPies = svg.selectAll(".arc")
.data(pie(data))
.enter()
.append("g")
.attr("class", "arc")
emptyPies.append("path")
.attr("d", function(d,i){
return i != 1 ? arc(d) : arc2(d);})
.style("fill", function(d, i) {
return color[i];
})
emptyPies.append("text")
.attr("transform", function(d) {
return "translate(" + arcLabel.centroid(d) + ")";
})
.text(function(d) {
return d.data;
});
</script>
A simple solution is to use multiple arc() but to do slice we can use arc.centroid() of 2nd arc. The following code will work in v5.
function onDrawPieChart() {
var data = [35, 20, 45];
var color = d3.schemeCategory10;
var width = 600;
var height = 600;
var radius = 100;
var pie = d3.pie().value((d) => d);
var arc = d3.arc().innerRadius(0).outerRadius(130);
var arc2 = d3.arc().innerRadius(0).outerRadius(20);
var slicedIndex = 1;
var pieData = pie(data);
var centroid = arc2.centroid(pieData[slicedIndex]);
var svg = d3
.select("body")
.append("svg")
.attr("viewBox", [-width / 2, -height / 2, width, height].join(" "))
.attr("width", width)
.attr("height", height)
.append("g");
svg
.selectAll("path")
.data(pieData)
.join("path")
.attr("fill", (d, i) => color[i])
.attr("d", (d) => arc(d))
.attr("transform", (d, i) => {
if (i === slicedIndex) {
var [x, y] = centroid;
return "translate(" + x + ", " + y + ")";
}
});
}

Add lines to SVG donut

I am working on creating a donut graph like this:
And this is the graph that I have from my JSFiddle.
var τ = 2 * Math.PI,
width = 100,
height = 100,
outerRadius = Math.min(width,height)/2,
innerRadius = (outerRadius/5)*4,
fontSize = (Math.min(width,height)/4);
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.cornerRadius(outerRadius - innerRadius)
.startAngle(0);
var svg = d3.select('.chart-container').append("svg")
.attr("width", '100%')
.attr("height", '100%')
.attr('viewBox','0 0 '+Math.min(width,height) +' '+Math.min(width,height) )
.attr('preserveAspectRatio','xMinYMin')
.append("g")
.attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");
var text = svg.append("text")
.text('0%')
.attr("text-anchor", "middle")
.style("font-size",fontSize+'px')
.attr("dy",fontSize/3)
.attr("dx",2);
var background = svg.append("path")
.datum({endAngle: τ})
.style("fill", "#7cc35f")
.attr("d", arc);
var midground = svg.append("path")
.datum({endAngle: 0 * τ})
.style("fill", "lightblue")
.attr("d", arc);
var foreground = svg.append("path")
.datum({endAngle: 0 * τ})
.style("fill", "#57893e")
.attr("d", arc);
midground.transition()
.duration(750)
.call(arcTween, 0.49 * τ);
foreground.transition()
.duration(750)
.call(arcTween, 0.25 * τ);
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
var interpolate = d3.interpolate(d.endAngle, newAngle);
return function(t) {
d.endAngle = interpolate(t);
text.text(Math.round((d.endAngle/τ)*100)+'%');
return arc(d);
};
});
}
I do not know how to add the four black lines to separate the quarters of the donut. Can anyone give me some insights on how to achieve that?
The pure D3 approach would use something like this:
svg.selectAll("line")
.data(d3.range(0, 360, 90))
.enter().append("line")
.attr("stroke", "black")
.attr("y1", outerRadius)
.attr("y2", innerRadius)
.attr("transform", function(d) { return "rotate(" + d + ")"});
Use d3.range() to create the array of values at which your marks should be placed. For this example this could also be written as [0, 90, 180, 270], but using d3.range() you could easily customize the number of marks to be placed around the perimeter of your donut by adjusting the step denoted by the third parameter. After binding the array, use the enter selection to append the lines to your chart. These require setting only y1 and y2 with x1 and x2 defaulting to 0 as the lines are afterwards rotated to their destination according to the bound values.
Have a look at this working example:
var τ = 2 * Math.PI,
width = 100,
height = 100,
outerRadius = Math.min(width,height)/2,
innerRadius = (outerRadius/5)*4,
fontSize = (Math.min(width,height)/4);
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius)
.cornerRadius(outerRadius - innerRadius)
.startAngle(0);
var svg = d3.select('.chart-container').append("svg")
.attr("width", '100%')
.attr("height", '100%')
.attr('viewBox','0 0 '+Math.min(width,height) +' '+Math.min(width,height) )
.attr('preserveAspectRatio','xMinYMin')
.append("g")
.attr("transform", "translate(" + Math.min(width,height) / 2 + "," + Math.min(width,height) / 2 + ")");
var text = svg.append("text")
.text('0%')
.attr("text-anchor", "middle")
.style("font-size",fontSize+'px')
.attr("dy",fontSize/3)
.attr("dx",2);
var background = svg.append("path")
.datum({endAngle: τ})
.style("fill", "#7cc35f")
.attr("d", arc);
var midground = svg.append("path")
.datum({endAngle: 0 * τ})
.style("fill", "lightblue")
.attr("d", arc);
var foreground = svg.append("path")
.datum({endAngle: 0 * τ})
.style("fill", "#57893e")
.attr("d", arc);
midground.transition()
.duration(750)
.call(arcTween, 0.49 * τ);
foreground.transition()
.duration(750)
.call(arcTween, 0.25 * τ);
svg.selectAll("line")
.data(d3.range(0, 360, 90))
.enter().append("line")
.attr("stroke", "black")
.attr("y1", outerRadius)
.attr("y2", innerRadius)
.attr("transform", function(d) { return "rotate(" + d + ")"});
function arcTween(transition, newAngle) {
transition.attrTween("d", function(d) {
var interpolate = d3.interpolate(d.endAngle, newAngle);
return function(t) {
d.endAngle = interpolate(t);
text.text(Math.round((d.endAngle/τ)*100)+'%');
return arc(d);
};
});
}
<script src="https://d3js.org/d3.v3.js"></script>
<div class="chart-container"></div>
you can use this function to calculate and draw the line:
var drawDonutLine = function(angle, overlap){
var overlap = overlap || 0;
angle = angle / (180 / Math.PI);
var innerR = (innerRadius-overlap);
var outerR = (outerRadius+overlap);
var beginX = Math.sin(angle)*innerR
var beginY = -Math.cos(angle)*innerR;
var endX = Math.sin(angle)*outerR;
var endY = -Math.cos(angle)*outerR;
svg.append('path')
.datum({})
.style("fill", "#000")
.attr('stroke', 'black')
.attr('stroke-width', 5)
.attr('d', "M "+beginX+" "+beginY+" L "+endX+" "+endY)
;
}
and use it like, where the first parameter is the angle (in degree), and the second parameter the overlapping in px
drawDonutLine(0,5);
see working example https://jsfiddle.net/2c7ajn8t/3/
I used https://www.dashingd3js.com/svg-paths-and-d3js as reference

Resources