Creating multiple progress circles d3.js - javascript

I'm looking to create multiple progress circles. (So, draw 3 circles from one data set)
I've been trying to adapt from this example, but as you will see, I've gone seriously wrong somewhere.
First steps I took was to change all the datums to data, as I will want the option to handle the data dynamically. Then, I tried to simplify the code so it was clearer/easier for me to understand. (I'm a d3 newbie!)
And now, I'm not sure what's going on, and was hoping someone could help me get to the end result?
Here is a fiddle and my code;
/*global d3*/
var width = 240,
height = 125,
min = Math.min(width, height),
oRadius = min / 2 * 0.8,
iRadius = min / 2 * 0.85,
color = d3.scale.category20();
var arc = d3.svg.arc()
.outerRadius(oRadius)
.innerRadius(iRadius);
var pie = d3.layout.pie().value(function(d) {
return d;
}).sort(null);
var data = [
[20],
[40],
[60]
];
// draw and append the container
var svg = d3.select("#chart").selectAll("svg")
.data(data)
.enter().append("svg")
.attr("width", width).attr("height", height);
svg.append('g')
.attr('transform', 'translate(75,62.5)')
.append('text').attr('text-anchor', 'middle').text("asdasdasdas")
// enter data and draw pie chart
var path = svg.selectAll("path")
.data(pie)
.enter().append("path")
.attr("class", "piechart")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc)
.each(function(d) {
this._current = d;
})
function render() {
// add transition to new path
svg.selectAll("path")
.data(pie)
.transition()
.duration(1000)
.attrTween("d", arcTween)
// add any new paths
svg.selectAll("path")
.data(pie)
.enter().append("path")
.attr("class", "piechart")
.attr("fill", function(d, i) {
return color(i);
})
.attr("d", arc)
.each(function(d) {
this._current = d;
})
// remove data not being used
svg.selectAll("path")
.data(pie).exit().remove();
}
render();
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
Thanks all!

You have a problem with where you are drawing your separate charts. All you need to do is add a translate to each one so they are in the center of their containers.
Add this after you create the paths :
.attr('transform', 'translate(' + width/2 + ',' +height/2 + ')')
width and height here are the containers dimensions, this will move each chart to the center of their container.
Update fiddle : http://jsfiddle.net/thatOneGuy/dbrehvtz/2/
Obviously, you probably know, if you want to add more values to each pie, just edit the data. For example :
var data = [
[20, 100, 100, 56, 23, 20, 100, 100, 56, 23 ],
[40],
[60]
];
New fiddle : http://jsfiddle.net/thatOneGuy/dbrehvtz/3/

Related

How to assign different color to each node on a sunburst?

I am creating a sunburst for big data. To make it more readable, I need to assign different color for each node (ideally different shades of the same color for every subtree).
I've already tried with :
d3.scaleSequential()
d3.scale.ordinal()
d3.scale.category20c()
I think it can work but I am not sure where to put it exactly. For the moment it works only with one color for every subtree.
var width = 500;
var height = 500;
var radius = Math.min(width, height) / 2;
var color = d3.scaleSequential().domain([1,10]).interpolator(d3.interpolateViridis);
var g = d3.select('svg')
.attr('width', width)
.attr('height', height)
.append('g')
.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
var partition = d3.partition() //.layout
.size([2 * Math.PI, radius]);
d3.json("file:///c:\\Users\\c1972519\\Desktop\\Stage\\tests_diagrams\\figure_4.8_ex3\\data2.json", function(error, nodeData){
if (error) throw error;
var root = d3.hierarchy(nodeData)
.sum(function(d){
return d.size;
});
partition(root);
var arc = d3.arc()
.startAngle(function(d) { return d.x0; })
.endAngle(function(d) { return d.x1; })
.innerRadius(function(d) { return d.y0; })
.outerRadius(function(d) { return d.y1; });
var arcs = g.selectAll('g')
.data(root.descendants())
.enter()
.append('g')
.attr("class", "node")
.append('path')
.attr("display", function (d) { return d.depth ? null : "none"; })
.attr("d", arc)
.style('stroke', '#fff')
.style("fill", function(d){return color(d)});
}
So I would like to have different shade on every subtree to make it more readable.
Anyone have an idea?
can you try with scaleLinear.
var x = d3.scaleLinear([10, 130], [0, 960]);
or
var color = d3.scaleLinear([10, 100], ["brown", "steelblue"]);
Example:
https://bl.ocks.org/starcalibre/6cccfa843ed254aa0a0d
Documentation:
https://github.com/d3/d3-scale/blob/master/README.md#scaleLinear
Linear Scales
d3.scaleLinear([[domain, ]range]) <>
Constructs a new continuous scale with the specified domain and range, the default interpolator and clamping disabled. If either domain or range are not specified, each defaults to [0, 1]. Linear scales are a good default choice for continuous quantitative data because they preserve proportional differences. Each range value y can be expressed as a function of the domain value x: y = mx + b.

How to add a legend to the motion chart

I use this script that creates a motion chart (see the original source code and a simplified fiddle). I wonder if it's possible to add the legend to this chart that would show the meaning of each color. The meaning should correspond to the field name from the input JSON.
Normally I create a legend as follows:
var colors = ["#F0E5FF","#E1CCFF","#C499FF","#AC79F2","#8D4CE5","#6100E5","#C94D8C"];
var colorScaleDomain = [300, 1000, 2000, 5000, 10000, 20000, 50000];
var colorScale = d3.scale.quantile()
.domain(colorScaleDomain)
.range(colors);
However, not sure how to adapt it to my current case when I use colorScale = d3.scale.category10().
Since d3.scale.category10() operates in a first-come first-served basis, that is, it adds values to the domain as new data comes in, you just need to pass the name in the same order that you painted the circles.
However, for this to work, you'll have to change your function color():
function color(d) {
return d.name;
}
Now, both the circles and the legends will have the same domain in the color scale.
Now, create the legends:
var legendGroup = svg.append("g")
.attr("transform", "translate(600,50)");
var legend = legendGroup.selectAll(".legend")
.data(SPX.map(d => d.name))
.enter()
.append("g")
.attr("transform", (d, i) => "translate(0," + 20 * i + ")")
var legendRects = legend.append("rect")
.attr("width", 10)
.attr("height", 10)
.attr("fill", d => colorScale(d));
var legendText = legend.append("text")
.attr("x", 14)
.attr("y", 8)
.text(d => d);
Here is your fiddle, I put the legends in the top-right corner: http://jsfiddle.net/8yd04e0p/

arc.centroid returning (NaN, NaN) in D3

Fair warning: I'm a D3 rookie here. I'm building a donut chart using D3 and all is well so far, except that the labels on the slices aren't aligning with the slices. Using the code below, the labels for each slice are rendered in the middle of the chart, stacked on top of each other so they're unreadable. I've dropped the arc.centroid in my transform attribute, but it's returning "NaN,NaN" instead of actual coordinates, and I can't understand where it's reading from that it's not finding a number. My innerRadius and outerRadius are defined in the arc variable. Any help?
(pardon the lack of a jsfiddle but I'm pulling data from a .csv here)
var width = 300,
height = 300,
radius = Math.min(width, height) / 2;
var color = ["#f68b1f", "#39b54a", "#2772b2"];
var pie = d3.layout.pie()
.value(function(d) { return d.taskforce1; })
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 85)
.outerRadius(radius);
var svg = d3.select("#pieplate").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.csv("data.csv", type, function(error, data) {
var path = svg.datum(data).selectAll("path")
.data(pie)
.enter().append("path")
.attr("fill", function(d, i) { return color[i]; })
.attr("d", arc)
.each(function(d) { this._current = d; }); // store the initial angles
var text = svg.selectAll("text")
.data(data)
.enter()
.append("text")
.attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text( function (d) { return d.taskforce1; })
.attr("font-family", "sans-serif")
.attr("font-size", "20px")
.attr("fill", "black");
d3.selectAll("a")
.on("click", switcher);
function switcher() {
var value = this.id;
var j = value + 1;
pie.value(function(d) { return d[value]; }); // change the value function
path = path.data(pie); // compute the new angles
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
textLabels = text.text( function (d) { return d[value]; });
}
});
function type(d) {
d.taskforce1 = +d.taskforce1;
d.taskforce2 = +d.taskforce2;
d.taskforce3 = +d.taskforce3;
return d;
}
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
Finally got it. The arc.centroid function expects data with precomputed startAngle and endAngle which is the result of pie(data). So the following helped me:
var text = svg.selectAll("text")
.data(pie(data))
followed by the rest of the calls. Note that you might have to change the way to access the text data that you want to display. You can always check it with
// while adding the text elements
.text(function(d){ console.log(d); return d.data.textAttribute })

update d3 pie chart with new data.json

I have a dynamic data source that creates a new json in the browser frequently.
I was able to create a pie chart from this json using the code below (also at this fiddle)
var data=[{"crimeType":"mip","totalCrimes":24},{"crimeType":"theft","totalCrimes":558},{"crimeType":"drugs","totalCrimes":81},{"crimeType":"arson","totalCrimes":3},{"crimeType":"assault","totalCrimes":80},{"crimeType":"burglary","totalCrimes":49},{"crimeType":"disorderlyConduct","totalCrimes":63},{"crimeType":"mischief","totalCrimes":189},{"crimeType":"dui","totalCrimes":107},{"crimeType":"resistingArrest","totalCrimes":11},{"crimeType":"sexCrimes","totalCrimes":24},{"crimeType":"other","totalCrimes":58}];
var width = 800,
height = 250,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(radius - 70);
var pie = d3.layout.pie()
.sort(null)
.value(function (d) {
return d.totalCrimes;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
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.crimeType);
});
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.crimeType;
});
This data updates frequenty so what would be the best way to update the pie? Look at this fiddle. Here I have another json called data2.
How could I simply replace data with data2 and have the pie animate/update?
Note: on some updates values could == 0
I have created a working version and have posted it here: http://www.ninjaPixel.io/StackOverflow/doughnutTransition.html (for some reason I couldn't get the transitions to play ball in fiddle, so have just posted it to my website instead).
To make the code clearer I have omitted your labelling, renamed 'data' to 'data1', and have stuck in some radio buttons to flip between the data arrays. The following snippet shows the important bits. You can get the whole code from my page above.
var svg = d3.select("#chartDiv").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("id", "pieChart")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
var path = svg.selectAll("path")
.data(pie(data1))
.enter()
.append("path");
path.transition()
.duration(500)
.attr("fill", function(d, i) { return color(d.data.crimeType); })
.attr("d", arc)
.each(function(d) { this._current = d; }); // store the initial angles
function change(data){
path.data(pie(data));
path.transition().duration(750).attrTween("d", arcTween); // redraw the arcs
}
// Store the displayed angles in _current.
// Then, interpolate from _current to the new angles.
// During the transition, _current is updated in-place by d3.interpolate.
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0);
return function(t) {
return arc(i(t));
};
}
You may find this code of Mike Bostock's helpful, it is where I learned how to do this.
Here are some other similar questions that might help:
How to update pie chart using d3.js
d3 pie chart transition with attrtween
simple d3.js pie chart transitions *without* data joins?
Adding new segments to a Animated Pie Chart in D3.js
https://groups.google.com/forum/#!msg/d3-js/2o5NTVjVJgA/AslmRSxXUAgJ

d3.js arc segment animation issue

I'm trying to create an animated arc segment with d3.js. I got the arc and the transition working, but while the animation is running, the arc gets distorted and I can't figure out why.
Here is what i have so far:
jsfiddle
var dataset = {
apples: [532, 284]
};
var degree = Math.PI/180;
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie().startAngle(-90*degree).endAngle(90*degree)
.sort(null);
var arc = d3.svg.arc()
.innerRadius(radius - 100)
.outerRadius(radius - 50);
var svg = d3.select("body").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.apples))
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
window.setInterval(dummyData, 2000);
function dummyData(){
var num = Math.round(Math.random() * 100);
var key = Math.floor(Math.random() * dataset.apples.length);
dataset.apples[key] = num;
draw();
};
function draw(){
svg.selectAll("path")
.data(pie(dataset.apples))
.transition()
.duration(2500)
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
}
As Richard explained, you're interpolating between the previously computed SVG path string and the newly computed string -- which is going to do some strange things -- rather than interpolating between the previous angle and the new angle, which is what you want.
You need to interpolate over the input and for each interpolated value map that to an SVG path string using your arc function. To do this, you need to store each previous datum somewhere and to use a custom tweening function, which you can find in examples in my previous comment.
1. Remember previous datum (initially):
.each(function(d) { this._current = d; });
2. Define a custom tweening function:
function arcTween(a) {
var i = d3.interpolate(this._current, a);
this._current = i(0); // Remember previous datum for next time
return function(t) {
return arc(i(t));
};
}
3. Use it:
.attrTween("d", arcTween)
Here's what it looks like: http://jsfiddle.net/Qh9X5/18/

Categories