Text is not appearing on arc donut in D3js - d3.js

Text is not appearing on the Donut Chart.Help me to fix this thing along with explanation.I am very new to D3js.
This is my sample code.
my html code is:
.arc text {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
and js code is:
var width = 600, height = 500, radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var arc = d3.svg.arc().outerRadius(radius - 10)
.innerRadius(radius - 70);
var pie = d3.layout.pie()
.value(function(d) {
return d.population;
});
var svg = d3.select("body").append("svg").attr("width", width).attr(
"height", height).append("g").attr("transform",
"translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("date.csv", type, function(error, data) {
if (error)
throw error;
var g = svg.selectAll(".arc").data(pie(data)).enter().append("g")
.attr("class", "arc");
g.append("path").attr("d", arc).style("fill", function(d, i) {
return color(i);
});
//.style("fill", function(d) { return color(d.date.age); });
g.append("text").attr("transform", function(d) {
return "translate(" + arc.centroid(d) + ")";
}).attr("dy", ".35em").text(function(d) {
return d.date.age;
});
});
function type(d) {
d.population = +d.population;
return d;
}
csv file is
age,population
5,2704659
13,4499890
17,2159981
24,3853788

Related

How to get day of week on left side of D3 calendar heat map

I'm trying to create a calendar heatmap with D3, very similar to the Github contribution calendar.
I can't get the day of week to align correctly. It seems to repeat for every month and doesn't have correct margins or alignment. I only want the days to display once, on the left side of the calendar.
Just like this:
Here is what mine looks like:
Here is my code:
<style>
#calendar {
margin: 20px;
}
.month {
margin-right: 8px;
}
.month-name {
font-size: 85%;
fill: #777;
font-family: Muli, san-serif;
}
.day.hover {
stroke: #6d6E70;
stroke-width: 2;
}
.day.focus {
stroke: #ffff33;
stroke-width: 2;
}
</style>
<div style="text-align:center;" id="calendar"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script>
function drawCalendar(dateData){
var weeksInMonth = function(month){
var m = d3.timeMonth.floor(month)
return d3.timeWeeks(d3.timeWeek.floor(m), d3.timeMonth.offset(m,1)).length;
}
//var minDate = new Date(2018, 12, 31);
var minDate = d3.min(dateData, function(d) { return new Date(2018, 12, 1 ) });
//var minDate = d3.min(dateData, function(d) { return new Date(d.day) });
console.log(minDate);
//var maxDate = new Date(2019, 11, 30);
var maxDate = d3.max(dateData, function(d) { return new Date(2019, 11, 30 ) });
console.log(maxDate);
var cellMargin = 2,
calY=10,//offset of calendar in each group
xOffset=-5,
dayName = ['Su','Mo','Tu','We','Th','Fr','Sa'],
cellSize = 20;
var day = d3.timeFormat("%w"),
week = d3.timeFormat("%U"),
format = d3.timeFormat("%Y-%m-%d"),
titleFormat = d3.utcFormat("%a, %d-%b"),
monthName = d3.timeFormat("%B"),
months= d3.timeMonth.range(d3.timeMonth.floor(minDate), maxDate);
var svg = d3.select("#calendar").selectAll("svg")
.data(months)
.enter().append("svg")
.attr("class", "month")
.attr("height", ((cellSize * 7) + (cellMargin * 8) + 20) ) // the 20 is for the month labels
.attr("width", function(d) {
var columns = weeksInMonth(d);
return ((cellSize * columns) + (cellMargin * (columns + 1)));
})
.append("g")
svg.append("text")
.attr("class", "month-name")
.attr("y", (cellSize * 7) + (cellMargin * 8) + 15 )
.attr("x", function(d) {
var columns = weeksInMonth(d);
return (((cellSize * columns) + (cellMargin * (columns + 1))) / 2);
})
.attr("text-anchor", "middle")
.text(function(d) { return monthName(d); })
//create day labels
var days = ['Su','Mo','Tu','We','Th','Fr','Sa'];
var dayLabels=svg.append("g").attr("id","dayLabels")
days.forEach(function(d,i) {
dayLabels.append("text")
.attr("class","dayLabel")
.attr("x",xOffset)
.attr("y",function(d) { return calY+(i * cellSize); })
.text(d);
})
var rect = svg.selectAll("rect.day")
.data(function(d, i) { return d3.timeDays(d, new Date(d.getFullYear(), d.getMonth()+1, 1)); })
.enter().append("rect")
.attr("class", "day")
.attr("width", cellSize)
.attr("height", cellSize)
.attr("rx", 3).attr("ry", 3) // rounded corners
.attr("fill", '#eaeaea') // default light grey fill
.attr("y", function(d) { return (day(d) * cellSize) + (day(d) * cellMargin) + cellMargin; })
.attr("x", function(d) { return ((week(d) - week(new Date(d.getFullYear(),d.getMonth(),1))) * cellSize) + ((week(d) - week(new Date(d.getFullYear(),d.getMonth(),1))) * cellMargin) + cellMargin ; })
.on("mouseover", function(d) {
d3.select(this).classed('hover', true);
})
.on("mouseout", function(d) {
d3.select(this).classed('hover', false);
})
.datum(format);
rect.append("title")
.text(function(d) { return titleFormat(new Date(d)); });
var lookup = d3.nest()
.key(function(d) { return d.day; })
.rollup(function(leaves) {
return d3.sum(leaves, function(d){ return parseInt(d.count); });
})
.object(dateData);
var scale = d3.scaleLinear()
.domain(d3.extent(dateData, function(d) { return parseInt(d.count); }))
.range([0.2,1]); // the interpolate used for color expects a number in the range [0,1] but i don't want the lightest part of the color scheme
rect.filter(function(d) { return d in lookup; })
.style("fill", function(d) { return d3.interpolateYlGn(scale(lookup[d])); })
.select("title")
.text(function(d) { return titleFormat(new Date(d)) + ": " + lookup[d]; });
}
d3.csv("dates.csv", function(response){
drawCalendar(response);
})
</script>
There is also an input csv file that contains the following values:
day,count
2019-05-12,171
2019-06-17,139
2019-05-02,556
2019-04-10,1
2019-05-04,485
2019-03-27,1
2019-05-26,42
2019-05-25,337
2019-05-23,267
2019-05-05,569
2019-03-31,32
2019-03-25,128
2019-05-13,221
2019-03-30,26
2019-03-15,3
2019-04-24,10
2019-04-27,312
2019-03-20,99
2019-05-10,358
2019-04-01,15
2019-05-11,199
2019-07-06,744
2019-05-08,23
2019-03-28,98
2019-03-29,64
2019-04-30,152
2019-03-21,148
2019-03-19,20
2019-05-07,69
2019-04-29,431
2019-04-25,330
2019-04-28,353
2019-04-18,9
2019-01-10,1
2019-01-09,2
2019-03-26,21
2019-05-27,18
2019-04-19,10
2019-04-06,1
2019-04-12,214
2019-05-03,536
2019-07-03,3
2019-06-16,1
2019-03-24,138
2019-04-26,351
2019-04-23,14
2019-05-01,19
2019-07-05,523
2019-05-22,3
2019-05-09,430
2019-05-24,472
2019-04-11,172
2019-03-17,7
2019-05-14,10
2019-05-06,449
2019-07-04,295
2019-05-15,12
2019-03-23,216
2019-03-18,47
2019-03-22,179
Typically you allow for a margin in your SVG, something like this:
const margin = { top: 10, right: 20, bottom: 10, left: 5 }
const svg = d3
.select('#chart')
.append('svg')
.attr('width', 900 + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
Basically you create an SVG element that is bigger than your drawing area, and then you move (translate) the chart in by the margins. Then your axis can appear in the margin

Updated d3v4 fiddle not working

I am upgrading this d3v3 pie chart code into d3v4 pie chart. But it is not working. Any insight would be highly appreciated.
v4 fiddle
The code is pretty much the same apart from these few changes i have made:
var pie = d3.pie()
var arc = d3.arc()
var outerarc = d3.arc()
In D3 v4.x, there is no more the magic of the enter().append, which changes the update selection in v3.x.
Now, you have to merge the selections:
//here you bind the data. This is the "update" selection
var slice = svg.select(".slices").selectAll("path.slice")
.data(pie(data), key);
//now comes your enter selection
slice.enter()
.append("path")
.attr("class", "slice")
.merge(slice)//from now on, "enter" + "update" selections
.style("fill", function(d) {
return color(d.data.label);
})
.transition().duration(1000)
.attrTween("d", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
})
Here is your code with the merged selections:
var svg = d3.select("body")
.append("svg")
.append("g")
svg.append("g")
.attr("class", "slices");
svg.append("g")
.attr("class", "labels");
svg.append("g")
.attr("class", "lines");
var width = 960,
height = 450,
radius = Math.min(width, height) / 2;
var pie = d3.pie()
.sort(null)
.value(function(d) {
return d.value;
});
var arc = d3.arc()
.outerRadius(radius * 0.8)
.innerRadius(radius * 0.4);
var outerArc = d3.arc()
.innerRadius(radius * 0.9)
.outerRadius(radius * 0.9);
svg.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var key = function(d) {
return d.data.label;
};
var color = d3.scaleOrdinal()
.domain(["Lorem ipsum", "dolor sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt"])
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
function randomData() {
var labels = color.domain();
return labels.map(function(label) {
return {
label: label,
value: Math.random()
}
});
}
change(randomData());
d3.select("button")
.on("click", function() {
change(randomData());
});
function change(data) {
/* ------- PIE SLICES -------*/
var slice = svg.select(".slices").selectAll("path.slice")
.data(pie(data), key);
slice.enter()
.append("path")
.attr("class", "slice")
.merge(slice)
.style("fill", function(d) {
return color(d.data.label);
})
.transition().duration(1000)
.attrTween("d", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
return arc(interpolate(t));
};
})
slice.exit()
.remove();
/* ------- TEXT LABELS -------*/
var text = svg.select(".labels").selectAll("text")
.data(pie(data), key);
function midAngle(d) {
return d.startAngle + (d.endAngle - d.startAngle) / 2;
}
text.enter()
.append("text")
.attr("dy", ".35em")
.text(function(d) {
return d.data.label;
}).merge(text)
.transition().duration(1000)
.attrTween("transform", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
var d2 = interpolate(t);
var pos = outerArc.centroid(d2);
pos[0] = radius * (midAngle(d2) < Math.PI ? 1 : -1);
return "translate(" + pos + ")";
};
})
.styleTween("text-anchor", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
var d2 = interpolate(t);
return midAngle(d2) < Math.PI ? "start" : "end";
};
});
text.exit()
.remove();
/* ------- SLICE TO TEXT POLYLINES -------*/
var polyline = svg.select(".lines").selectAll("polyline")
.data(pie(data), key);
polyline.enter()
.append("polyline")
.merge(polyline)
.transition().duration(1000)
.attrTween("points", function(d) {
this._current = this._current || d;
var interpolate = d3.interpolate(this._current, d);
this._current = interpolate(0);
return function(t) {
var d2 = interpolate(t);
var pos = outerArc.centroid(d2);
pos[0] = radius * 0.95 * (midAngle(d2) < Math.PI ? 1 : -1);
return [arc.centroid(d2), outerArc.centroid(d2), pos];
};
});
polyline.exit()
.remove();
};
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
width: 960px;
height: 500px;
position: relative;
}
svg {
width: 100%;
height: 100%;
}
path.slice {
stroke-width: 2px;
}
polyline {
opacity: .3;
stroke: black;
stroke-width: 2px;
fill: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<button>Randomize</button>

Error: <path> attribute d: Expected number, "….35254915624212LNaN,NaNZ"

I am trying to build pie-chart using D3js. I am getting an error while running the code and pie chart is not coming properly.
This is the code:
var svg = d3.select('#pie_chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var total=0;
for(var a=0;a<data.length;a++){
total=total+parseInt(data[a].count);
}
var pie_data=[];
for( var a=0;a<data.length;a++){
pie_data[a]=(data[a].count/total)*100;
}
var arc = d3.arc().outerRadius(150);
var pie = d3.pie()
.value(function(d,i) {
return pie_data[i];
}).sort(null);
var path = svg.selectAll('path')
.data(pie(data))
.enter().append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return data[i].color;
});
Set innerRadius property of d3 arc.
var arc = d3.arc().outerRadius(150).innerRadius(0);
var width = 500,
height = 400;
var data = [{
count: 10,
color: 'black'
}, {
count: 20,
color: 'green'
}, {
count: 30,
color: 'blue'
}];
var svg = d3.select('#pie_chart')
.append('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + (width / 2) +
',' + (height / 2) + ')');
var total = 0;
data.forEach(function(d) {
total += d.count;
});
var pie_data = [];
for (var a = 0; a < data.length; a++) {
pie_data[a] = (data[a].count / total) * 100;
}
var arc = d3.arc().outerRadius(150).innerRadius(0);
var pie = d3.pie()
.sort(null)
.value(function(d) {
return d;
});
var path = svg.selectAll('path')
.data(pie(pie_data))
.enter().append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return data[i].color;
});
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="pie_chart"></div>

d3 how to tween inner radius for pie chart

I need to animate pie chart into a donut chart (or ring chart).
Here is my code:
var arc = d3.svg.arc().outerRadius(radius-margin).innerRadius(0)
var arc2 = d3.svg.arc().outerRadius(radius-margin).innerRadius(60)
var path = pie_chart.selectAll('path')
.data(pie(data))
.enter()
.append('path')
.attr('d', arc)
.attr('fill', function(d, i) {
return color_scale(d.data.device)
})
.transition().attr('d', arc2)
Some times it's working but sometimes it is not. I have tried to apply transition to arc but not working.
var arc2 = d3.svg.arc().outerRadius(radius-margin).innerRadius(0).transition().innerRadius(60)
I would write my own arcTween function for this to take complete control of the transition:
function arcTween(d) {
var i = d3.interpolateNumber(0, radius-70); //<-- radius of 0 to donut
return function(t) {
var r = i(t),
arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(r); //<-- create arc
return arc(d); //<-- return arc path
};
}
Full code:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 500,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.category10();
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.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 data = [10, 20, 30, 40];
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d, i) {
return color(i);
})
.transition()
.delay(100)
.duration(5000)
.attrTween("d", arcTween);
function arcTween(d) {
var i = d3.interpolateNumber(0, radius-70);
return function(t) {
var r = i(t),
arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(r);
return arc(d);
};
}
</script>
</body>
Or just give someone a headache:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.arc text {
font: 10px sans-serif;
text-anchor: middle;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var width = 500,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.category10();
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.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 data = [10, 20, 30, 40];
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
var arcs = g.append("path")
.attr("d", arc)
.style("fill", function(d, i) {
return color(i);
});
(function repeat() {
arcs.transition()
.duration(500)
.attrTween("d", arcTweenOut)
.transition()
.duration(500)
.attrTween("d", arcTweenIn)
.each('end', repeat)
})();
function arcTweenOut(d) {
var i = d3.interpolateNumber(0, radius-70);
return function(t) {
var r = i(t),
arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(r);
return arc(d);
};
}
function arcTweenIn(d) {
var i = d3.interpolateNumber(radius-70, 0);
return function(t) {
var r = i(t),
arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(r);
return arc(d);
};
}
</script>
</body>

D3.JS - how do I add gridlines to my pie chart

I have extended the pie-chart example at:
with pies that vary in radius depending on a percentage. I would like to add gridlines (circles) every 20 percent, but I can't figure out how.
here is the updated csv:
age,population,percent
<5,2704659,67
5-13,4499890,38
14-17,2159981,91
18-24,3853788,49
25-44,14106543,71
45-64,8819342,88
=65,612463,64
and here is the updated code with pie-parts of different radius:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
body {
font: 10px sans-serif;
background: #333;
}
.arc path {
stroke: #fff;
stroke-width: 2px;
}
.arc grid {
stroke: #fff;
stroke-width: 1;
stroke-dasharray: 5,5;
}
.arc text {
fill:#fff;
font-size:12px;
font-weight:bold;
}
.arc line {
stroke: #fff;
}
</style>
<body>
<script src="d3.js"></script>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2 - 10;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(function(d) { return 50 + (radius - 50) * d.data.percent / 100; })
.innerRadius(20);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
var grid = d3.svg.area.radial()
.radius(150);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("data.csv", function(error, data) {
data.forEach(function(d) {
d.population = +d.population;
d.percent = d.percent;
});
var g = svg.selectAll(".arc")
.data(pie(data))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.age); });
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; });
});
</script>
First set the number of ticks:
var numTicks = 5; // Each tick is 20%
Then create the data to create the gridlines:
var sdat = [];
for (i=0; i<=numTicks; i++) {
sdat[i] = (radius/numTicks) * i;
}
And then you can use a function to create the radial gridlines, and you can call it from within the d3.csv block:
addCircleAxes = function() {
var circleAxes, i;
svg.selectAll('.circle-ticks').remove();
circleAxes = svg.selectAll('.circle-ticks')
.data(sdat)
.enter().append('svg:g')
.attr("class", "circle-ticks");
// radial tick lines
circleAxes.append("svg:circle")
.attr("r", String)
.attr("class", "circle")
.style("stroke", "#CCC")
.style("opacity", 0.5)
.style("fill", "none");
// Labels for each circle
circleAxes.append("svg:text")
.attr("text-anchor", "center")
.attr("dy", function(d) { return d - 5 })
.style("fill", "#fff")
.text(function(d,i) { return i * (100/numTicks) });
};
An example is here: http://bl.ocks.org/3994129
(Borrowed from: http://kreese.net/blog/2012/08/26/d3-js-creating-a-polar-area-diagram-radial-bar-chart/)

Resources