I have a list of images and a list of image titles. I want to be able to show a hover state (change css) for the title when I mouse over its corresponding image, but I cannot figure out how to connect the two pieces of data. My code is below. I have it so that when you click on the top number the information appears beneath.
<!DOCTYPE html>
<html>
<head>
<script src="d3.v2.js"></script>
<title>Untitled</title>
</head>
<body>
<script type="text/javascript" >
function barStack(d) {
var l = d[0].length
while (l--) {
var posBase = 0, negBase = 0;
d.forEach(function(d) {
d=d[l]
d.size = Math.abs(d.y)
if (d.y<0) {
d.y0 = negBase
negBase-=d.size
} else
{
d.y0 = posBase = posBase + d.size
}
})
}
d.extent= d3.extent(d3.merge(d3.merge(d.map(function(e) { return e.map(function(f) { return [f.y0,f.y0-f.size]})}))))
return d
}
var ratiodata = [[{y:3.3}],[{y:-1.5}]]
var imageList = [
[3.3, 28, -1.5, 13, 857, 3, 4, 7, [{paintingfile:"676496.jpg", title:"Dessert1"}, {paintingfile:"676528.jpg", title: "Dessert2"}]
]]
var h=400
var w=1350
var margin=25
var color = d3.scale.category10()
var div = d3.select("body").append("div")
.attr("class", "imgtooltip")
.style("opacity", 0);
var x = d3.scale.ordinal()
.domain(['255'])
.rangeRoundBands([margin,w-margin], .1)
var y = d3.scale.linear()
.range([h-margin,0+margin])
var xAxis = d3.svg.axis().scale(x).orient("bottom").tickSize(6, 0)
var yAxis = d3.svg.axis().scale(y).orient("left")
barStack(ratiodata)
y.domain(ratiodata.extent)
var svg = d3.select("body")
.append("svg")
.attr("height",h)
.attr("width",w)
svg.selectAll(".series")
.data(ratiodata)
.enter()
.append("g")
.classed("series",true)
.style("fill","orange")
.selectAll("rect").data(Object)
.enter()
.append("rect")
.attr("x",function(d,i) { return x(x.domain()[i])})
.attr("y",function(d) { return y(d.y0)})
.attr("height",function(d) { return y(0)-y(d.size)})
.attr("width",x.rangeBand());
svg.selectAll("text")
.data(imageList)
.enter()
.append("text")
.text(function(d) {
return d[0];
})
.attr("x", function(d, i) {
return x(x.domain()[i]) + x.rangeBand() / 2;
})
.attr("y", function(d) {
return h - (32.1100917431*d[0] +150);
})
.attr("font-size", "16px")
.attr("fill", "#000")
.attr("text-anchor", "middle")
//.on("click", function(d) {console.log(d[1]);})
.on("click", function(d) {
//Update the tooltip position and value
d3.selectAll("ul")
.remove();
d3.selectAll("li")
.remove();
d3.select("#PaintingDetails")
.append("ul")
.selectAll("li")
.data(d[8])
.enter()
.append("li")
.text(function(d){
return (d.title);
});
d3.select("#imageBox")
.append("ul")
.selectAll("li")
.data(d[8])
.enter()
.append("li")
.classed("Myimageslist",true)
.append("img")
.classed("Myimages",true)
.attr("src", function(d){
return ("http://images.tastespotting.com/thumbnails/" + d.paintingfile);
})
.attr("align", "top");
d3.select(".Myimages")
.on("mouseover", function(){
d3.select("#PaintingDetails")
.selectAll("li")
.classed("selected", true)
});
});
svg.append("g").attr("class","axis x").attr("transform","translate (0 "+y(0)+")").call(xAxis);
// svg.append("g").attr("class","axis y").attr("transform","translate ("+x(margin)+" 0)").call(yAxis);
</script>
<div id="PaintingDetails"></div>
<div id="imageBox"></div>
</body>
</html>
The quick and dirty solution would be to simply use the index of the data element to figure out which title matches which image:
d3.selectAll(".Myimages")
.on("mouseover", function(d, i) {
d3.select("#PaintingDetails")
.selectAll("li")
.classed("selected", function(e, j) { return j == i; })
});
Related
Very new to D3 and coming from R but looking to develop some interactive choropleth maps.
I'm wanting to develop this zoomable choropleth: https://bl.ocks.org/cmgiven/d39ec773c4f063a463137748097ff52f
into something like this V5 choropleth with easily attachable data: https://bl.ocks.org/denisemauldin/3436a3ae06f73a492228059a515821fe
I can mainipulate the V5 choropleth fairly easily, still figuring out how to adjust continuous scale to a discrete scale but I don't really know how to build the zoomable svg in V5.
I think in your question you are asking about continuous scale, here is a code snippet for continuous scaling for an zoomable choropleth, What is just apply the same mechanism in this bl.ocks.org just wrap everything in <g> group tag and apply the zoom on this <g> tag:
const zoom = d3.zoom()
.scaleExtent([1, 8])
.on('zoom', zoomed);
svg.call(zoom);
function zoomed() {
zoomG.selectAll('path') // To prevent stroke width from scaling
.attr('transform', d3.event.transform);
}
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var unemployment = d3.map();
var stateNames = d3.map();
var path = d3.geoPath();
var x = d3.scaleLinear()
.domain([1, 10])
.rangeRound([600, 860]);
var color = d3.scaleThreshold()
.domain(d3.range(0, 10))
.range(d3.schemeBlues[9]);
var g = svg.append("g")
.attr("class", "key")
.attr("transform", "translate(0,40)");
g.selectAll("rect")
.data(color.range().map(function(d) {
d = color.invertExtent(d);
if (d[0] == null) d[0] = x.domain()[0];
if (d[1] == null) d[1] = x.domain()[1];
return d;
}))
.enter().append("rect")
.attr("height", 8)
.attr("x", function(d) { return x(d[0]); })
.attr("width", function(d) { return x(d[1]) - x(d[0]); })
.attr("fill", function(d) { return color(d[0]); });
g.append("text")
.attr("class", "caption")
.attr("x", x.range()[0])
.attr("y", -6)
.attr("fill", "#000")
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text("Unemployment rate");
g.call(d3.axisBottom(x)
.tickSize(13)
.tickFormat(function(x, i) { return i ? x : x + "%"; })
.tickValues(color.domain()))
.select(".domain")
.remove();
var promises = [
d3.json("https://d3js.org/us-10m.v1.json"),
d3.tsv("https://gist.githubusercontent.com/denisemauldin/3436a3ae06f73a492228059a515821fe/raw/954210175a18c646eb751d59e04d5a4814fe3b03/us-state-names.tsv", function(d) {
stateNames.set(d.id, d.name)
}),
d3.tsv("https://gist.githubusercontent.com/denisemauldin/3436a3ae06f73a492228059a515821fe/raw/954210175a18c646eb751d59e04d5a4814fe3b03/map.tsv", function(d) {
unemployment.set(d.name, +d.value);
})
]
Promise.all(promises).then(ready)
function ready([us]) {
let zoomG = svg.append("g");
zoomG.append("g")
.attr("class", "counties")
.selectAll("path")
.data(topojson.feature(us, us.objects.states).features)
.enter().append("path")
.attr("fill", function(d) {
var sn = stateNames.get(d.id)
d.rate = unemployment.get(stateNames.get(d.id)) || 0
var col = color(d.rate);
if (col) {
return col
} else {
return '#ffffff'
}
})
.attr("d", path)
.append("title")
.text(function(d) {
return d.rate + "%"; });
zoomG.append("path")
.datum(topojson.mesh(us, us.objects.states, function(a, b) { return a !== b; }))
.attr("class", "states")
.attr("d", path);
const zoom = d3.zoom()
.scaleExtent([1, 8])
.on('zoom', zoomed);
svg.call(zoom);
function zoomed() {
zoomG.selectAll('path') // To prevent stroke width from scaling
.attr('transform', d3.event.transform);
}
}
.counties {
fill: none;
}
.states {
fill: none;
stroke: #fff;
stroke-linejoin: round;
}
<!DOCTYPE html>
<meta charset="utf-8">
<svg width="960" height="600"></svg>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/topojson.v2.min.js"></script>
I want to get bounding boxes for each country from a topojson, but when I add them as svg rectangles they are bundled together towards 0,0.
Ive re-read the API and played around with the order of the bound coordinates, but that didn't change anything! Also, I tried to use the SVG method getBBox() on the country paths but that produced the same result.
Any ideas?
var width = 700,
height = 400,
bboxes = [];
d3.queue()
.defer(d3.json, "data/world.topojson")
.await(ready);
//Map projection
var proj = d3.geoMercator()
.scale(100)
.center([-0.0018057527730242487, 11.258678472759552]) //projection center
.translate([width / 2, height / 2]) //translate to center the map in view
//Generate paths based on projection
var myPath = d3.geoPath().projection(proj);
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//Group for the map features
var map = svg.append("g")
.attr("class", "map");
function ready(error, geodata) {
if (error) return console.log(error); //unknown error, check the console
//Create a path for each map feature in the data
map.selectAll("path")
.data(topojson.feature(geodata, geodata.objects.subunits).features) //generate features from TopoJSON
.enter()
.append("path")
.attr("class", "country")
.attr("id", function(d) {
return d.id;
})
.attr("d", myPath);
bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.subunits).features);
svg.selectAll("rect")
.data(bboxes)
.enter()
.append("rect")
.attr("id", function(d){
return d.id;
})
.attr("class", "bb")
.attr("x1", function(d) {
return d.x;
})
.attr("y1", function(d) {
return d.y;
})
.attr("width", function(d) {
return d.width;
})
.attr("height", function(d) {
return d.height;
})
}
function boundingExtent(features) {
var bounds= [];
for (var x in features) {
var boundObj = {};
thisBounds = myPath.bounds(features[x]);
boundObj.id = features[x].id;
boundObj.x = thisBounds[0][0];
boundObj.y = thisBounds[0][1];
boundObj.width = thisBounds[1][0] - thisBounds[0][0];
boundObj.height = thisBounds[1][1] - thisBounds[0][1];
boundObj.path = thisBounds;
bounds.push(boundObj)
}
return bounds;
}
function boundExtentBySvg(){
var countries = svg.selectAll(".country")
countries.each(function(d){
var box = d3.select(this).node().getBBox();
bboxes.push({id: d.id, x: box.x, y : box.y, width: box.width, height : box.height})
})
}
In these lines:
.attr("x1", function(d) {
return d.x;
})
.attr("y1", function(d) {
return d.y;
})
rect does not have an attribute of x1 or y1, I think you meant just x and y.
Here's your code running (note, I switched out the topojson file which caused slight code changes):
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
<script data-require="topojson.min.js#3.0.0" data-semver="3.0.0" src="https://unpkg.com/topojson#3.0.0"></script>
</head>
<body>
<svg width="700" height="400"></svg>
<script>
var width = 700,
height = 400,
bboxes = [];
d3.queue()
.defer(d3.json, "https://unpkg.com/world-atlas#1/world/110m.json")
.await(ready);
//Map projection
var proj = d3.geoMercator()
.scale(100)
.center([-0.0018057527730242487, 11.258678472759552]) //projection center
.translate([width / 2, height / 2]) //translate to center the map in view
//Generate paths based on projection
var myPath = d3.geoPath().projection(proj);
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
//Group for the map features
var map = svg.append("g")
.attr("class", "map");
function ready(error, geodata) {
if (error) return console.log(error); //unknown error, check the console
//Create a path for each map feature in the data
map.selectAll("path")
.data(topojson.feature(geodata, geodata.objects.countries).features) //generate features from TopoJSON
.enter()
.append("path")
.attr("class", "country")
.attr("id", function(d) {
return d.id;
})
.attr("d", myPath);
bboxes = boundingExtent(topojson.feature(geodata, geodata.objects.countries).features);
svg.selectAll("rect")
.data(bboxes)
.enter()
.append("rect")
.attr("id", function(d) {
return d.id;
})
.attr("class", "bb")
.attr("x", function(d) {
return d.x;
})
.attr("y", function(d) {
return d.y;
})
.attr("width", function(d) {
return d.width;
})
.attr("height", function(d) {
return d.height;
})
.style("fill", "none")
.style("stroke", "steelblue");
}
function boundingExtent(features) {
var bounds = [];
for (var x in features) {
var boundObj = {};
thisBounds = myPath.bounds(features[x]);
boundObj.id = features[x].id;
boundObj.x = thisBounds[0][0];
boundObj.y = thisBounds[0][1];
boundObj.width = thisBounds[1][0] - thisBounds[0][0];
boundObj.height = thisBounds[1][1] - thisBounds[0][1];
boundObj.path = thisBounds;
bounds.push(boundObj)
}
console.log(bounds)
return bounds;
}
function boundExtentBySvg() {
var countries = svg.selectAll(".country")
countries.each(function(d) {
var box = d3.select(this).node().getBBox();
bboxes.push({
id: d.id,
x: box.x,
y: box.y,
width: box.width,
height: box.height
})
})
}
</script>
</body>
</html>
I am trying to add labels properly over arcs. Because the arc angles are so small, the labels can't fit over the arcs and "bend". How can i make the labels fit over the arcs keeping the same font size, same radius and same number of arcs?
<script src="http://d3js.org/d3.v4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<style>
.layer_1 {
stroke: none;
}
.layer_o {
stroke: none;
}
</style>
</head>
<body>
<script>
//build test data
var dict = []; // create an empty array
var angle = 0;
var nb_arcs = 255;
var max_radius = 200;
var colorScale = d3.scaleOrdinal(d3["schemeCategory10"])
for (var i = 0; i < nb_arcs; i++) {
var outer_radius_1 = Math.random() * max_radius;
dict.push({
id: i,
layer: 1,
inner_radius: 0,
outer_radius: outer_radius_1,
start_angle: angle,
end_angle: angle + 2 * Math.PI / nb_arcs
});
dict.push({
id: nb_arcs + i,
layer: 2,
inner_radius: outer_radius_1,
outer_radius: max_radius,
end_angle: 2,
start_angle: angle,
end_angle: angle + 2 * Math.PI / nb_arcs
});
angle = angle + 2 * Math.PI / nb_arcs;
}
var svg = d3.select("body").append("svg")
.attr("width", 960)
.attr("height", 500)
.append("g")
.attr("transform", "translate(480,250)");
var g = svg.selectAll("g").enter().append("g");
var path = svg.selectAll("path")
.data(dict)
.enter().append("path")
.attr("id", function(d) {
return d.id;
})
.attr("class", function(d) {
if (d.layer == 1) {
return "layer_1";
} else {
return "layer_o";
}
})
.attr("d", d3.arc()
.innerRadius(function(d) {
return d.inner_radius;
})
.outerRadius(function(d) {
return d.outer_radius;
})
.startAngle(function(d) {
return d.start_angle;
})
.endAngle(function(d) {
return d.end_angle;
}))
.attr("fill", function(d) {
return colorScale(d.layer);
})
.style('stroke', function(d) {
return colorScale(d.layer);
})
.style('stroke-width', '0.3');
svg.selectAll("text")
.data(dict)
.enter()
.append("text")
.attr('dy', function(d) {
if (d.id % 2 == 0) {
return -13;
} else {
return -5;
}
})
.attr("class", "labelText")
.append("textPath") //append a textPath to the text element
.attr("xlink:href", function(d) {
return "#" + d.id;
})
.style("font-size", "5px")
.text(function(d) {
if (d.layer == 2) {
return "#" + d.id;
} else {
return "";
}
})
.style("text-anchor", "middle")
.attr('startOffset', function(d) {
if (d.id % 2 == 0) {
return 3;
} else {
return 0;
}
})
.attr("fill", "black");
</script>
</body>
</html>
I have created a d3 force layout, and it works very well. Now I will add a group of data to my graph. I hope I could control the center of my new nodes. For example, supposed the center is (100,100), I hope the new nodes lay out into rectangle area like [(50,50) to (150,150)] as a whole.
var width = 500,
height = 500;
var nodes = [{id:0, n:'Tom'}, {id:1, n:'Join'}, {id:2, n:'John'}, {id:3, n:'Bob'}, {id:4, n:'4'}, {id:5, n:'5'}, {id:6, n:'6'}];
var links = [{source:0,target:1},{source:0,target:2},{source:0,target:3},{source:0,target:4},{source:0,target:5},{source:1,target:5},{source:1,target:6}];
// init force
var force = d3.layout.force()
.charge(-120)
.linkDistance(120)
.size([width, height]);
// init svg
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// set tick function
force.on("tick", function () {
d3.selectAll(".link").attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
// controll the coordinates here
d3.selectAll(".node").attr("transform", function(d){
if(d.flag == 1){
d.x = Math.max(50, Math.min(150, d.x));
d.y = Math.max(50, Math.min(150, d.y));
}
return "translate("+d.x+","+d.y+")";
});
}).on('end', function(){
svg.selectAll(".node").each(function(d){d.fixed=true;});
});
function setData(ns, ls){
var update = svg.selectAll(".link").data(ls);
update.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
update.exit().remove();
update = svg.selectAll(".node").data(ns);
update.enter().append("g")
.attr("class", "node")
.attr("id", function(d){return d.id})
.call(force.drag)
.call(function(p){
p.append("image")
.attr("class", "nodeimage")
.attr("width", "30px")
.attr("height", "30px")
.attr("x", "-15px")
.attr("y", "-15px");
p.append("text")
.attr("class", "nodetext")
.attr("dx", "-10px")
.attr("dy", "20px")
.style("font-size", "15px")
.text(function(d){return d.n});
});
update.exit().remove();
update.selectAll(".nodeimage")
.each(function() {
d3.select(this).datum(d3.select(this.parentNode).datum());
})
.attr("xlink:href", function(d){
var img;
if(d.flag == 1){
img = "http://www.gravatar.com/avatar/1eccef322f0beef11e0e47ed7963189b/?default=&s=80"
}else{
img = "http://www.gravatar.com/avatar/a1338368fe0b4f3d301398a79c171987/?default=&s=80";
}
return img;
});
force.nodes(ns)
.links(ls)
.start();
}
//init
setData(nodes, links);
setTimeout(function(){
//generate new data and merge to old data
nodes = nodes.concat(generateNewData());
setData(nodes, links);
//how do i control the coordinate of new nodes?
}, 3000);
function generateNewData(){
var ns = [];
for(var i = 0; i < 10; i++){
ns.push({id:i+100,n:'n'+i,flag:1});
}
return ns;
}
Here is my demo of jsfiddle:http://jsfiddle.net/cs4xhs7s/4/
The latest demo shows that the nodes can display in the rectangle, however, their coordinates are the same. I hope it is an available force layout.
https://jsfiddle.net/wpnq15mf/1/
var width = 500,
height = 500;
var nodes = [{id:0, n:'Tom'}, {id:1, n:'Join'}, {id:2, n:'John'}, {id:3, n:'Bob'}, {id:4, n:'4'}, {id:5, n:'5'}, {id:6, n:'6'}];
var links = [{source:0,target:1},{source:0,target:2},{source:0,target:3},{source:0,target:4},{source:0,target:5},{source:1,target:5},{source:1,target:6}];
// init force
var force = d3.layout.force()
.charge(-500)
.linkDistance(120)
.gravity(0.1)
.size([width, height]);
// init svg
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// set tick function
force.on("tick", function () {
d3.selectAll(".link").attr("x1", function (d) {
return d.source.x;
})
.attr("y1", function (d) {
return d.source.y;
})
.attr("x2", function (d) {
return d.target.x;
})
.attr("y2", function (d) {
return d.target.y;
});
// controll the coordinates here
d3.selectAll(".node").attr("transform", function(d){
if(d.flag == 1){
d.x = Math.max(50, Math.min(150, d.x));
d.y = Math.max(50, Math.min(150, d.y));
}
return "translate("+d.x+","+d.y+")";
});
}).on('end', function(){
svg.selectAll(".node").each(function(d){d.fixed=true;});
});
function setData(ns, ls){
var update = svg.selectAll(".link").data(ls);
update.enter().append("line")
.attr("class", "link")
.style("stroke-width", 1);
update.exit().remove();
update = svg.selectAll(".node").data(ns);
update.enter().append("g")
.attr("class", "node")
.attr("id", function(d){return d.id})
.call(force.drag)
.call(function(p){
p.append("image")
.attr("class", "nodeimage")
.attr("width", "30px")
.attr("height", "30px")
.attr("x", "-15px")
.attr("y", "-15px");
p.append("text")
.attr("class", "nodetext")
.attr("dx", "-10px")
.attr("dy", "20px")
.style("font-size", "15px")
.text(function(d){return d.n});
});
update.exit().remove();
update.selectAll(".nodeimage")
.each(function() {
d3.select(this).datum(d3.select(this.parentNode).datum());
})
.attr("xlink:href", function(d){
var img;
if(d.flagx == 1){
img = "http://www.gravatar.com/avatar/1eccef322f0beef11e0e47ed7963189b/?default=&s=80"
}else{
img = "http://www.gravatar.com/avatar/a1338368fe0b4f3d301398a79c171987/?default=&s=80";
}
return img;
});
force.nodes(ns)
.links(ls)
.start();
}
//init
setData(nodes, links);
setTimeout(function(){
//generate new data and merge to old data
nodes = nodes.concat(generateNewData());
links = links.concat(generateNewLinks());
setData(nodes, links);
//how do i control the coordinate of new nodes?
}, 3000);
function generateNewData(){
var ns = [];
ns.push({id:6,n:'n'+i,flag:1, flagx:1});
for(var i = 1; i < 10; i++){
ns.push({id:i+6,n:'n'+i, flagx:1});
}
return ns;
}
function generateNewLinks(){
var ns = [];
ns.push({source:7,target:8});
ns.push({source:7,target:9});
ns.push({source:7,target:10});
ns.push({source:7,target:11});
ns.push({source:7,target:12});
ns.push({source:7,target:13});
ns.push({source:7,target:14});
ns.push({source:7,target:15});
ns.push({source:7,target:16});
return ns;
}
.node {
stroke: #fff;
stroke-width: 1.5px;
}
.link {
stroke: #999;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I've been trying to get the update chart function to work... what am I doing wrong?
I've created a function to build the chart.
Then an update function once input boxes are changed - so if a user changes the data and then hits update.
I am unable to try and access the existing pie chart and update it/animate it with the correct data.
$.Core.doughnutCommon ={
init: function(){
var that = this;
var colourtheme = {
"spectrum" : ["#e87424", "#ebb700", "#007c92"]
};
$('[data-doughnut-pie-common="true"]').each(function(index) {
that.bindInputEvents($(this));
var holder = $(this)[0];
var data = that.generateData(holder);
console.log("data", data);
var theme = $(this).data("theme");
var colours = colourtheme[theme];
var radius = 64;
that.buildchart(holder, index, data, colours, radius);
});
},
bindInputEvents: function(holder){
var that = this;
holder.find('.updatechart').click(function(e) {
e.preventDefault();
that.updatechart(holder);
});
holder.find('.dataset li input').keyup(function() {
$(this).parent().parent().find('.value').text($(this).val());
});
},
generateData: function(holder){
var that = this;
var json = new Array();
var keysObj = {};
var legendsarray = new Array();
$(holder).find('.dataset li').each(function(index) {
var key = $(this).find('.key').text();
var value = $(this).find('.value').text();
//__key obj
var localKeyObj = {};
localKeyObj[key] = "";
//__legend array build
var stream = {
"name" : key,
"population" : value
}
jQuery.extend(keysObj, localKeyObj);
legendsarray.push(stream);
});
var obj ={
"legends": legendsarray
};
jQuery.extend(obj, keysObj);
json.push(obj);
return json;
},
updatechart: function(holder){
var that = this;
console.log("holder", holder);
var data = that.generateData(holder);
console.log("data hold", data);
var pieId = holder.find(".pie").attr("id");
//draw arc paths
//var svg = d3.select('#'+pieId);
var arc_group = d3.select('#'+pieId+' .sliceholder');
var color = d3.scale.ordinal();
var arc = d3.svg.arc()
.outerRadius(64)
.innerRadius(64 - 20);
paths = arc_group.selectAll("path").data(data[0].legends);
paths.enter().append("svg:path")
.attr("class", "arc")
.attr("d", arc)
.style("fill", function(d) {
console.log("d", d);
return color(d.name);
})
.transition()
.duration(500);
//.attrTween("d", arcTween);
paths
.transition()
.duration(500);
//.attrTween("d", arcTween);
paths.exit()
.transition()
.duration(500)
//.attrTween("d", arcTween);
.remove();
function arcTween(d) {
var i = d3.interpolate(this._current, d);
this._current = i(0);
return function(t) { return arc(i(t)); };
}
},
buildchart: function(holder, index, data, colours, radius){
var padding = 10;
var color = d3.scale.ordinal()
.range(colours);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 20);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
color.domain(
d3.keys(data[0]).filter(function(key) {
return key !== "legends";
})
);
var svg = d3.select(holder).selectAll(".pie")
.data(data)
.enter().append("svg")
.attr("class", "pie")
.attr("id", "pie"+index)
.attr("width", radius * 2)
.attr("height", radius * 2)
.append("g")
.attr("class", "sliceholder")
.attr("transform", "translate(" + radius + "," + radius + ")");
svg.selectAll(".arc")
.data(function(d) { return pie(d.legends); })
.enter().append("path")
.attr("class", "arc")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.name); });
var legend = d3.select(holder).append("svg")
.attr("class", "legend")
.attr("width", radius * 1.7)
.attr("height", radius * 2)
.selectAll("g")
.data(color.domain().slice().reverse())
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * 25 + ")"; });
legend.append("rect")
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", 24)
.attr("y", 9)
.attr("dy", ".35em")
.text(function(d) { return d; });
var totalUnits = svg.append("svg:text")
.attr("class", "units")
.attr("dy", 5)
.attr("text-anchor", "middle") // text-align: right
.text("Chart title");
}
};
The html is as follows
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="d3.v3.min.js"></script>
<script>
$.Core ={
init: function(){
console.log("test");
$.Core.doughnutCommon.init();//iniate doughnut read only
}
};
</script>
<script type="text/javascript" src="doughnut.common.js"></script>
<script>
$(document).ready(function() {
$.Core.init();
});
</script>
<div class="doughnut_pie common" data-doughnut-pie-common="true" data-theme="spectrum">
<form>
<ul class="dataset">
<li>
<span class="key">Equities</span>
<span class="value">50</span>
<span class="varbox"><input type="text" value="50"></span>
</li>
<li>
<span class="key">Bonds</span>
<span class="value">30</span>
<span class="varbox"><input type="text" value="30"></span>
</li>
<li>
<span class="key">Gilts</span>
<span class="value">20</span>
<span class="varbox"><input type="text" value="20"></span>
</li>
</ul>
<button class="updatechart">UPDATE</button>
</form>
</div>
There are a couple of problems with your code. First, the selector
var arc_group = d3.select('#'+pieId+' .sliceholder');
doesn't work because the g element with class sliceholder is a subelement of the SVG. You need
var arc_group = d3.select('#'+pieId+' > .sliceholder');
Second, you can't pass in the raw data when updating, you need to process it with a pie layout first. That is,
paths = arc_group.selectAll("path").data(data[0].legends);
won't work, you need
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.population; });
paths = arc_group.selectAll("path").data(pie(data[0].legends));
Third, you've missed some initialisation when copying the arcTween code. You need to set the initial values for ._current:
svg.selectAll(".arc")
.data(function(d) { return pie(d.legends); })
.enter().append("path")
...
.each(function(d) { this._current = d; });
Working jsfiddle here.