D3 Pie Chart: Arctween in mouseOver doesn't work - javascript

Problem: The Arctween function will not work on the .on("mouseOver").
Intention: When hovering the arcs in the Pie Chart a highlight needs to start (opacity etc.) and information needs (infoHover) to show, next to the Arctween that I also want to activate.
I am aware that the code is not perfect at all, I'm just experimenting with d3.js.
Thanks in advance!
Javascript:
d3.json("dataExample.json", function (data) {
var width = 260,
height = 260;
var outerRadius = height / 2 - 20,
innerRadius = outerRadius / 3,
cornerRadius = 10;
colors = d3.scale.category20c();
var tempColor;
var pie = d3.layout.pie()
.padAngle(.02)
.value(function(d) {
return d.value;
})
var arc = d3.svg.arc()
.padRadius(outerRadius)
.innerRadius(innerRadius);
var infoHover = d3.select('#chart').append('div')
.style('position', 'absolute')
.style('padding', '0 30px')
.style('opacity', 0)
function arcTween(outerRadius, delay) {
return function() {
d3.select(this).transition().delay(delay).attrTween("d", function(d) {
var i = d3.interpolate(d.outerRadius, outerRadius);
return function(t) { d.outerRadius = i(t); return arc(d); };
});
};
}
var svg = d3.select("#chart").append("svg")
.data(data)
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.selectAll('path').data(pie(data))
.enter().append('path')
.attr('fill', function(d, i) {
return colors(i);
})
.each(function(d) { d.outerRadius = outerRadius - 20; })
.attr('d', arc)
.on("mouseover", function(d) {
infoHover.transition()
.style('opacity', .9)
.style('left', '85px')
.style('top', '120px')
infoHover.html(d.value + '%')
d3.selectAll("path")
.transition()
.duration(500)
.style("opacity", .18)
d3.select(this)
.transition()
.duration(500)
.style('opacity', 1)
.style('cursor', 'pointer')
arcTween(outerRadius, 0);
})
.on("mouseout", function(d) {
d3.selectAll("path")
.transition()
.duration(500)
.style("opacity", 1)
d3.select(this)
.style('opacity', 1)
arcTween(outerRadius - 20, 150);
});
});

Your arcTween returns a function your need to call:
arcTween(outerRadius, 0).call(this);

Related

Switch d3 donut arc on selection

I have more than one donut in my page, each donut will have a thinner portion (like unfilled) and another arc colored.
When user clicks on the colored arc, it should have a white border. And if user selects other arc (unfilled) the unfilled area get filled with color, changes the width like the other one and will have border, same time the filled one gets unfilled. To summarize the arc colored portion should get switched on selection.
Can I achieve this by applying class/styles? In one page there should be only one arc selected at a time, all other selections will be cleared.
// data
var dataset = [{
color: "#5FC5EA",
value: 70
}, {
color: "transparent",
value: 30
}];
// size
var width = 460,
z
height = 300,
radius = Math.min(width, height) / 2;
var pie = d3.layout.pie()
.sort(null).value(function(d) {
return d.value;
});
// thin arc
var arc1 = d3.svg.arc()
.innerRadius(radius - 20)
.outerRadius(radius - 11);
// main arc
var arc = d3.svg.arc()
.innerRadius(radius - 30)
.outerRadius(radius);
// set svg
var svg = d3.select("#d3-setup-donut").append("svg")
.attr("class", 'donut-chart')
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")")
.on('mouseout', function() {
d3.selectAll('.donut-tooltip').style('display', 'none');
});
// tooltip
var div = d3.select("body")
.append("div")
.attr("class", "donut-tooltip");
// draw thinner arc
var path = svg.selectAll(".background")
.data(pie([{
color: "#222427",
value: 1
}]))
.enter().append("path")
.attr("class", "background")
.attr("fill", function(d, i) {
return d.data.color;
})
.attr("d", arc1)
.on('click', function(d, i) {
//
})
.on("mousemove", function(d, i) {
var mouseVal = d3.mouse(this);
div.style("display", "none");
div.html(d.data.label + " : " + d.value)
.style("left", (d3.event.pageX - 40) + "px")
.style("top", (d3.event.pageY - 35) + "px")
.style("opacity", 1)
.style("display", "block");
})
.on("mouseout", function() {
div.html(" ").style("display", "none");
});
// draw main arc
var path = svg.selectAll(".foreground")
.data(pie(dataset))
.enter().append("path")
.attr("class", "foreground")
.attr("fill", function(d, i) {
return d.data.color;
})
.attr("d", arc)
.on('click', function(d, i) {
d3.select(this)
.classed('selected', true);
})
.on("mousemove", function(d, i) {
var mouseVal = d3.mouse(this);
div.style("display", "none");
div.html(d.data.label + " : " + d.value)
.style("left", (d3.event.pageX - 40) + "px")
.style("top", (d3.event.pageY - 55) + "px")
.style("opacity", 1)
.style("display", "block");
})
.on("mouseout", function() {
div.html(" ").style("display", "none");
});
// draw inner text
svg.append("text")
.text('60%')
.attr("class", "donut-inner-val")
//.attr("x", radius/12 - 30)
//.attr("y", radius/12 - 10);
svg.append("text")
.text('in progress')
.attr("class", "donut-inner-text")
.attr("x", (radius / 12) - 35)
.attr("y", (radius / 12) + 10);
JSFiddle
Try this Code
.on('click', function(d, i) {
d3.selectAll(".foreground").classed('selected', false);
if(d3.select(this).classed("active")){
d3.select(this)
.classed('selected', true);
}else{
d3.selectAll(".foreground").classed("active", false);
d3.select(this).classed("active",true);
d3.select(this)
.classed('selected', true);
}
})
DEMO

D3.js pie chart animate counterwise

As the title says. How can I reverse the animation path in a pie (D3.js). As default, the pie renders clockwise with animation. How do I reverse it?
See picture example.
JS here:
var pie = d3.layout.pie()
.sort(null)
.startAngle(1 * Math.PI)
.endAngle(3 * Math.PI)
.value(function (d) { return d.percentage; });
g.append("path")
.attr("d", arc)
.style("fill", function (d) { return d.data.color; })
.attr({
"fill": function (d) {
return d.data.color;
}
})
.transition()
.duration(1000)
.attrTween("d", function (d) {
var i = d3.interpolate(d.startAngle, d.endAngle);
return function (t) {
d.endAngle = i(t);
return arc(d);
}
});
Just swap endAngle with startAngle:
.transition()
.duration(1000)
.attrTween("d", function (d) {
var i = d3.interpolate(d.endAngle, d.startAngle);
return function (t) {
d.startAngle = i(t);
return arc(d);
}
});
Check the snippet:
var dataset = {
apples: [5345, 2879, 1997, 2437, 4045],
};
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie()
.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)
.transition()
.duration(1000)
.attrTween("d", function (d) {
var i = d3.interpolate(d.endAngle, d.startAngle);
return function (t) {
d.startAngle = i(t);
return arc(d);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

SVG line out of arc starting position - d3.js

I'm trying to achieve this
but this is currently what I have
Essentially all I need to do is figure out how to have the lines emanating out from the circle starting at the arc start.
My question is exactly that, how can I translate the arc starting position into the x1,y1 attribute of an svg line. Below is the code that I currently have pertaining to drawing the lines:
// Draw lines emanating out
g.append('line')
.attr('class', 'outer-line')
.attr('x1', function(d) {
return 0;
})
.attr('x2', 0)
.attr('y1', -radius)
.attr('y2', -radius-150)
.attr('stroke', function(d, i) {
return color(i);
})
.attr('stroke-width','2')
.attr("transform", function(d) {
return "rotate(" + (d.startAngle+d.endAngle)/2 * (180/Math.PI) + ")";
});
If I understand your problem correctly, you can use just d.startAngle:
g.attr("transform", function(d) {
return "rotate(" + d.startAngle * (180/Math.PI) + ")";
});
Check here an example (click on "run code snippet"):
var dataset = [300, 200, 400, 200, 300, 100, 50];
var width = 460,
height = 300,
radius = Math.min(width, height) / 2;
var color = d3.scale.category20();
var pie = d3.layout.pie()
.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))
.enter().append("path")
.attr("fill", function(d, i) { return color(i); })
.attr("d", arc);
var g = svg.selectAll(".groups")
.data(pie(dataset))
.enter()
.append("g");
g.append('line')
.attr('class', 'outer-line')
.attr('x1', 0)
.attr('x2', 0)
.attr('y1', -radius + 50)
.attr('y2', -radius)
.attr('stroke', 'black')
.attr('stroke-width','2')
.attr("transform", function(d) {
return "rotate(" + d.startAngle * (180/Math.PI) + ")";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

Change single chord color in chord diagram using D3.js

D3 and Javascript newbie here. I'd like to change the color of a single chord in a chord diagram that is rendered with D3. Ideally, this color can be arbitrary, with no relationship to the source/destination entities of the chord.
How do I identify a single chord so I can later access it to fill it?
Here's an image (poorly edited with an image editor) with the desired effect (green chord).
var matrix = [
[11975, 5871, 8916, 2868],
[ 1951, 10048, 2060, 6171],
[ 8010, 16145, 8090, 8045],
[ 1013, 990, 940, 6907]
];
var chord = d3.layout.chord()
.padding(.05)
.sortSubgroups(d3.descending)
.matrix(matrix);
var width = 960,
height = 500,
innerRadius = Math.min(width, height) * .41,
outerRadius = innerRadius * 1.1;
var fill = d3.scale.ordinal()
.domain(d3.range(4))
.range(["#000000", "#FFDD89", "#957244", "#F26223"]);
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
svg.append("g").selectAll("path")
.data(chord.groups)
.enter().append("path")
.style("fill", function(d) { return fill(d.index); })
.style("stroke", function(d) { return fill(d.index); })
.attr("d", d3.svg.arc().innerRadius(innerRadius).outerRadius(outerRadius))
.on("mouseover", fade(.1))
.on("mouseout", fade(1));
var ticks = svg.append("g").selectAll("g")
.data(chord.groups)
.enter().append("g").selectAll("g")
.data(groupTicks)
.enter().append("g")
.attr("transform", function(d) {
return "rotate(" + (d.angle * 180 / Math.PI - 90) + ")"
+ "translate(" + outerRadius + ",0)";
});
ticks.append("line")
.attr("x1", 1)
.attr("y1", 0)
.attr("x2", 5)
.attr("y2", 0)
.style("stroke", "#000");
ticks.append("text")
.attr("x", 8)
.attr("dy", ".35em")
.attr("transform", function(d) { return d.angle > Math.PI ? "rotate(180)translate(-16)" : null; })
.style("text-anchor", function(d) { return d.angle > Math.PI ? "end" : null; })
.text(function(d) { return d.label; });
svg.append("g")
.attr("class", "chord")
.selectAll("path")
.data(chord.chords)
.enter().append("path")
.attr("d", d3.svg.chord().radius(innerRadius))
.style("fill", function(d) { return fill(d.target.index); })
.style("opacity", 1)
.on("mouseover", function(){
d3.select(this).style("opacity", 0.3);
})
.on("mouseout", function(){
d3.select(this).style("opacity", 1);
});
// Returns an array of tick angles and labels, given a group.
function groupTicks(d) {
var k = (d.endAngle - d.startAngle) / d.value;
return d3.range(0, d.value, 1000).map(function(v, i) {
return {
angle: v * k + d.startAngle,
label: i % 5 ? null : v / 1000 + "k"
};
});
}
// Returns an event handler for fading a given chord group.
function fade(opacity) {
return function(g, i) {
svg.selectAll(".chord path")
.filter(function(d) { return d.source.index != i && d.target.index != i; })
.transition()
.style("opacity", opacity);
};
}
body {
font: 10px sans-serif;
}
.chord path {
fill-opacity: .67;
stroke: #000;
stroke-width: .5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I've just added functionality for mouse over and mouse out,
svg.append("g")
.attr("class", "chord")
.selectAll("path")
.data(chord.chords)
.enter().append("path")
.attr("d", d3.svg.chord().radius(innerRadius))
.style("fill", function(d) { return fill(d.target.index); })
.style("opacity", 1)
.on("mouseover", function(){
d3.select(this).style("opacity", 0.3);
})
.on("mouseout", function(){
d3.select(this).style("opacity", 1);
});
In the above code see the mouseover and mouseout callbacks,
Here I'm just changing the opacity, if you want to change the color, use fill attribute to fill the color.
Hope you are looking for this.
If not ask me for more.
:D

rotate points from csv on d3 orthogonal projection

I have been trying to project a heat map with data loaded from csv onto a orthogonal projection on D3. While rotating the earth (i.e. D3, orthogonal projection), the points/circles remain static. I have tried many combinations but failed to figure out what is missing.
Basically, i need the small circles move along the path of countries.
Here is the complete code :
<script>
var width = 600,
height = 500,
sens = 0.25,
focused;
//Setting projection
var projection = d3.geo.orthographic()
.scale(245)
.rotate([0,0])
.translate([width / 2, height / 2])
.clipAngle(90);
var path = d3.geo.path()
.projection(projection);
//SVG container
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height);
// Define the gradient
var gradient = svg.append("svg:defs")
.append("svg:linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "100%")
.attr("spreadMethod", "pad");
// Define the gradient colors
gradient.append("svg:stop")
.attr("offset", "0%")
.attr("stop-color", "#FFFF00")
.attr("stop-opacity", 0);
gradient.append("svg:stop")
.attr("offset", "100%")
.attr("stop-color", "#FF0000")
.attr("stop-opacity", 1);
//Adding water
svg.append("path")
.datum({type: "Sphere"})
.attr("class", "water")
.attr("d", path)
var countryTooltip = d3.select("body").append("div").attr("class", "countryTooltip"),
countryList = d3.select("body").append("select").attr("name", "countries");
queue()
.defer(d3.json, "world-110m.json")
.defer(d3.tsv, "world-110m-country-names.tsv")
.await(ready);
//Main function
function ready(error, world, countryData) {
var countryById = {},
countries = topojson.feature(world, world.objects.countries).features;
//Adding countries to select
countryData.forEach(function(d) {
countryById[d.id] = d.name;
option = countryList.append("option");
option.text(d.name);
option.property("value", d.id);
});
//circles for heatmap are coming from the csv below
d3.csv("cities.csv", function(error, data) {
svg.selectAll("circle")
.data(data)
.enter()
.append("a")
.attr("xlink:href", function(d) {
return "https://www.google.com/search?q="+d.city;}
)
.append("circle")
.attr("cx", function(d) {
return projection([d.lon, d.lat])[0];
})
.attr("cy", function(d) {
return projection([d.lon, d.lat])[1];
})
.attr("r", 5.5)
.attr('fill', 'url(#gradient)');
var world = svg.selectAll("path.circle")
.data(countries) //countries from the tsc file is used to populate the names
.enter().append("path")
.attr("class", "land")
.attr("d", path)
//.attr('fill', 'url(#gradient)')
//Drag event
.call(d3.behavior.drag()
.origin(function() { var r = projection.rotate(); return {x: r[0] / sens, y: -r[1] / sens}; })
.on("drag", function() {
var rotate = projection.rotate();
projection.rotate([d3.event.x * sens, -d3.event.y * sens, rotate[2]]);
svg.selectAll("path.land").attr("d", path);
svg.selectAll(".focused").classed("focused", focused = false);
}))
//Mouse events
.on("mouseover", function(d) {
countryTooltip.text(countryById[d.id])
.style("left", (d3.event.pageX + 7) + "px")
.style("top", (d3.event.pageY - 15) + "px")
.style("display", "block")
.style("opacity", 1);
})
.on("mouseout", function(d) {
countryTooltip.style("opacity", 0)
.style("display", "none");
})
.on("mousemove", function(d) {
countryTooltip.style("left", (d3.event.pageX + 7) + "px")
.style("top", (d3.event.pageY - 15) + "px");
});
});//closing d3.csv here
//Country focus on option select
d3.select("select").on("change", function() {
var rotate = projection.rotate(),
focusedCountry = country(countries, this),
p = d3.geo.centroid(focusedCountry);
svg.selectAll(".focused").classed("focused", focused = false);
//Globe rotating
(function transition() {
d3.transition()
.duration(2500)
.tween("rotate", function() {
var r = d3.interpolate(projection.rotate(), [-p[0], -p[1]]);
return function(t) {
projection.rotate(r(t));
svg.selectAll("path").attr("d", path)
.classed("focused", function(d, i) { return d.id == focusedCountry.id ? focused = d : false; });
//svg.selectAll("circle").attr("d", data)
//.classed("focused", function(d, i) { return d.id == focusedCountry.id ? focused = d : false; });
};
})
})();
});
function country(cnt, sel) {
for(var i = 0, l = cnt.length; i < l; i++) {
if(cnt[i].id == sel.value) {return cnt[i];}
}
};
};
</script>
Please help.
Thank you in advance
Here is an option, using point geometries:
.enter().append('path')
.attr('class', 'circle_el')
.attr('fill', function(d) {return d.fill; })
.datum(function(d) {
return {type: 'Point', coordinates: [d.lon, d.lat], radius: some_radius};
})
.attr('d', path);
This is cool because you will update the circles simultaneously with a path redraw. And in addition it will account for the projection as a sphere, not showing circles that should be on the non-visible side of the sphere. I got the idea from this post by Jason Davies.

Categories