d3 x scale and labels at the bottom - javascript

I'm trying to build a vertical drill down bar graph. I'm referring to this link https://observablehq.com/#d3/hierarchical-bar-chart. The graph in the link is a horizontal bar chart but I'm building a vertical one. I have managed to build the graph but there is an issue with the xAxis positioning. I'm trying to position it down like how we do in the normal bar chart but it seems to be not working.My code and image are given below.
As you can see from the image the xAxis and the labels are on the top. I want it in the bottom. I have used d3.axisBottom but it doesnt seem to be working.
code
var margin = { top: 30, right: 50, bottom: 30, left: 50 },
width = 400 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var y:any = d3.scaleLinear()
.range([height, 0]);
var x = d3.scaleBand()
.range([0, width])
// .domain(flare.map(function(d) { return d.name; }))
// .padding(0.2);
var barWidth = 25;
var color:any = d3.scaleOrdinal()
.range(["steelblue"]);
var duration = 750,
delay = 25;
var yAxis:any = d3.axisLeft(y);
var xAxis:any = d3.axisBottom(x);
var svg: any = d3.select("#Area")
.append("svg")
.attr('preserveAspectRatio', 'xMinYMin meet')
.attr(
'viewBox',
'0 0 ' +
(width + margin.left + margin.right) +
' ' +
(height + margin.top + margin.bottom)
)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")")
svg.append("rect")
.attr("class", "background")
.attr("width", width + margin.left + margin.right)
.attr("height", height)
.on("click", up);
svg.append("g")
.attr("class", "y axis");
svg.append("g")
.attr("class", "x axis")
.append("line")
.attr("x1", "100%")
.call(d3.axisBottom(x));
var root = d3.hierarchy(flare)
.sum(d => d['size']);
y.domain([0, root.value]).nice();
down(root, 0);
function down(d, i) {
if (!d.children) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(p => p === d)
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
var enter = bar(d)
// .attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", color(true));
// Update the y-scale domain.
y.domain([0, d3.max(d.children, d => d['value'])]).nice();
// Update the y-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Update the x-axis.
svg.selectAll(".x.axis").transition()
.duration(duration)
.call(xAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay((d, i) => i * delay)
.attr("transform", (d, i) => `translate(${barWidth * i * 1.2 + 5}, 0)`);
// Transition entering text.
enterTransition.select("text")
.style("fill-opacity", 1);
// Transition entering rects to the new y-scale.
enterTransition.select("rect")
.attr("height", d => height - y(d['value']))
.attr("width", barWidth)
.attr("y", d => y(d['value']))
.attr("x", d => x(d['data'].name))
.attr("width", barWidth)
.style("fill", d => color(!!d['children']));
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new y-scale.
exitTransition.selectAll("rect")
.attr("height", d => height - y(d['value']))
.attr("width", barWidth)
.attr("y", d => y(d['value']))
.attr("x", d => x(d['data'].name))
.attr("width", barWidth)
// Rebind the current node to the background.
svg.select(".background")
.datum(d)
.transition()
.duration(end);
d.index = i;
}
function up(d) {
if (!d.parent) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", (d, i) => `translate(${barWidth * i * 1.2 + 5}, 0)`)
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", d => color(!!d['children']))
.filter(p => p === d)
.style("fill-opacity", 1e-6);
// Update the y-scale domain.
y.domain([0, d3.max(d.parent.children, d => d['value'])]).nice();
// Update the y-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new y-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("height", d => height - y(d['value']))
.attr("width", barWidth)
.attr("y", d => y(d['value']))
.attr("x", d => x(d['data'].name))
.attr("width", barWidth)
.on("end", function (p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay((d, i) => i * delay)
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("height", d => height - y(d['value']))
.attr("width", barWidth)
.attr("y", d => y(d['value']))
.attr("x", d => x(d['data'].name))
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition()
.duration(end)
.remove();
// Rebind the current parent to the background.
svg.select(".background")
.datum(d.parent)
.transition()
.duration(end);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("g", ".x.axis")
.attr("class", "enter")
.attr("transform", "translate(0,0)")
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", d => !d['children'] ? null : "pointer")
.on("click", down);
bar.append("rect")
.attr("height", d => height - y(d['value']))
.attr("width", barWidth)
.attr("y", d => y(d['value']))
.attr("x", d => x(d['data'].name))
bar.append("text")
.attr("x", -15)
.attr("y", -barWidth / 2)
.attr("dx", ".35em")
.attr("transform", "rotate(90)")
.style("text-anchor", "end")
.text(d => d['data'].name);
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var y0 = 0;
return function (d) {
var ty = `translate(${barWidth * i * 1.2 + 5}, ${y0})`;
y0 += y(d.value);
return ty;
};
}

axisBottom just dictates the direction of the ticks and labels, you still need to move it in place.
Change this:
svg.append("g")
.attr("class", "x axis")
.append("line")
.attr("x1", "100%")
.call(d3.axisBottom(x));
To:
svg.append('g')
.attr('class','x axis')
.attr('transform','translate(0,' + height + ')') // Move the axis to the bottom
.call(d3.axisBottom(x))
.append("line")
.attr("x1", "100%")

Related

Rotate Hierarchical Bar chart

I am using hierarchical D3.JS Bar chart.
here is the link
Click here to see the chart
I want to rotate this chart as vertical position.
The following is code is used to rotate the chart as vertical position
//svg Rotate
svg.attr("transform", function (d) {
return "rotate(-90)"
});
But chart is going towards top of the browser.
Click here to see the chart after that code has changed
when i add the following code.
svg.attr("transform", function (d) {
return "rotate(-90deg)"
});
The chart going inside to the browser the attachment
see the chart after i add -90 deg
Can anyone tell me how to show the display as per my requirement.
Thanks
Vinoth,
As #Terry said in his comment this is an X-Y problem. You are asking "how do I rotate the chart?"; when you should be asking "how do I redraw the chart to be vertical?". Well, here it is all refactored:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: 10px sans-serif;
}
rect.background {
fill: white;
}
.axis {
shape-rendering: crispEdges;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 10, right: 120, bottom: 120, left: 120},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var y = d3.scale.linear()
.range([height, 0]);
var barHeight = 20;
var color = d3.scale.ordinal()
.range(["steelblue", "#ccc"]);
var duration = 750,
delay = 25;
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", up);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, " + height + ")")
.append("line")
.attr("x1", "100%");
svg.append("g")
.attr("class", "y axis");
d3.json("https://jsonblob.com/api/f577d19c-0f2b-11e7-a0ba-09040711ce47", function(error, root) {
if (error) throw error;
partition.nodes(root);
y.domain([0, root.value]).nice();
down(root, 0);
});
function down(d, i) {
if (!d.children || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
var enter = bar(d)
.attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", color(true));
// Update the x-scale domain.
y.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", function(d, i) { return "translate(" + barHeight * i * 2.5 + "," + 0 + ")"; });
// Transition entering text.
enterTransition.select("text")
.style("fill-opacity", 1);
// Transition entering rects to the new y-scale.
enterTransition.select("rect")
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new y-scale.
exitTransition.selectAll("rect")
.attr("height", function(d) { return height - y(d.value); });
// Rebind the current node to the background.
svg.select(".background")
.datum(d)
.transition()
.duration(end);
d.index = i;
}
function up(d) {
if (!d.parent || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", function(d, i) { return "translate(" + barHeight * i * 2.5 + "," + 0 + ")"; })
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function(d) { return color(!!d.children); })
.filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Update the y-scale domain.
y.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();
// Update the y-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new y-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("height", function(d) { return height - y(d.value); })
.attr("y", function(d) { return y(d.value); })
.each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("height", function(d) { return height - y(d.value); })
.attr("y", function(d) { return y(d.value); })
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition()
.duration(end)
.remove();
// Rebind the current parent to the background.
svg.select(".background")
.datum(d.parent)
.transition()
.duration(end);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("g", ".x.axis")
.attr("class", "enter")
.attr("transform", "translate(15,0)")
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", function(d) { return !d.children ? null : "pointer"; })
.on("click", down);
bar.append("text")
.attr("x", barHeight / 2)
.attr("y", height + 10)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d.name; })
.attr("transform", "rotate(45 " + (barHeight / 2) + " " + (height + 10) + ")")
bar.append("rect")
.attr("width", barHeight)
.attr("height", function(d) { return height - y(d.value); })
.attr("y", function(d) { return y(d.value); });
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var y0 = 0;
return function(d) {
var tx = "translate(" + barHeight * i * 1.5 + "," + y0 + ")";
y0 += y(d.value);
return tx;
};
}
</script>

Draw wordcloud for each point in scatterplot

I create a scatterplot which is defined on the following data (note that only first two fields are currently using for plotting):
var data = [[5,3,"{'text':'word1',size:4},{'text':'word2','size':1}"],
[3,5,"{'text':'word3',size:5},{'text':'word4','size':4}"],
[1,4,"{'text':'word1',size:3},{'text':'word2','size':5},{'text':'word3','size':2}"],
[2,3,"{'text':'word2',size:1},{'text':'word3','size':5}"]];
Next, when we click on each particular point in the scatterplot the application should attach a wordcloud which is defined from words stored in the 3rd field of the data variable. I use Jason Davies's implementation of wordcloud. Currently (for demo purposes), the wordcloud is generating onlyfrom the static data stored in variable frequency_list. The current code is also stored on JSFiddle.
Any idea how to proceed?
var data = [[5,3,"{'text':'word1',size:4},{'text':'word2','size':1}"],
[3,5,"{'text':'word3',size:5},{'text':'word4','size':4}"],
[1,4,"{'text':'word1',size:3},{'text':'word2','size':5},{'text':'word3','size':2}"],
[2,3,"{'text':'word2',size:1},{'text':'word3','size':5}"]];
var margin = {top: 20, right: 15, bottom: 60, left: 60},
width = 500 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;
var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[0]; })])
.range([ 0, width ]);
var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([ height, 0 ]);
var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')
var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')
// Draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');
main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);
// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');
main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);
var g = main.append("svg:g");
g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return x(d[0]); } )
.attr("cy", function (d) { return y(d[1]); } )
.attr("r", 5)
.on("mouseover", function(){d3.select(this).style("fill", "red")})
.on("mouseout", function(){d3.select(this).style("fill", "black")});
// FUNCTION TO DISPLAY CIRCLE
g.on('mouseover', function(){
div.style("display", "block")
d3.select("krog").style("fill", "orange");
generate();
});
g.on('mouseout', function(){
//div.style("display", "none")
div.select("svg").remove();
});
var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("display", "none");
// Functions to draw wordcloud
var frequency_list = [{"text":"study","size":40},{"text":"motion","size":15},{"text":"forces","size":10},{"text":"electricity","size":15},{"text":"movement","size":10},{"text":"relation","size":5},{"text":"things","size":10},{"text":"force","size":5},{"text":"ad","size":5}];
var color = d3.scale.linear()
.domain([0,1,2,3,4,5,6,10,15,20,100])
.range(["#ddd", "#ccc", "#bbb", "#aaa", "#999", "#888", "#777", "#666", "#555", "#444", "#333", "#222"]);
// Generates wordcloud
function generate(){
d3.layout.cloud().size([800, 300])
.words(frequency_list)
.rotate(0)
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
}
function draw(words) {
d3.select("div").append("svg")
.attr("width", 850)
.attr("height", 350)
.attr("class", "wordcloud")
.append("g")
// without the transform, words words would get cutoff to the left and top, they would
// appear outside of the SVG area
.attr("transform", "translate(320,200)")
.selectAll("text")
.data(words)
.enter().append("text")
.style("font-size", function(d) { return d.size + "px"; })
.style("fill", function(d, i) { return color(i); })
.attr("transform", function(d) {
return "translate(" + [d.x, d.y] + ")rotate(" + d.rotate + ")";
})
.text(function(d) { return d.text; });
}
You have a couple of problems here.
First, your data has strings for the words. I changed that for an array of objects:
var data = [[5,3,[{'text':'word1',size:4},{'text':'word2','size':1}]],
[3,5,[{'text':'word3',size:5},{'text':'word4','size':4}]],
[1,4,[{'text':'word1',size:3},{'text':'word2','size':5},{'text':'word3','size':2}]],
[2,3,[{'text':'word2',size:1},{'text':'word3','size':5}]]];
After that, I changed the function draw: instead of appending a new div every time you hover a circle, it just change the div content:
div.append("svg")
.attr("width", 300)
.attr("height", 300)
.attr("class", "wordcloud")
.append("g")
But now comes the most important change:
You are displaying the wordcloud every time the user hover a circle, but you're calling the mouseover for the group element. That way, we cannot access the data bound to each specific circle.
Instead of that, we'll set a variable for the circles:
var circle = g.selectAll("scatter-dots")
.data(data)
.enter()
.append("svg:circle");
Thus, we can get the data for each hovered circle, which is the third element in the array:
circle.on('mouseover', function(d){
div.style("display", "block")
d3.select("krog").style("fill", "orange");
generate(d[2]);//here, d[2] is the third element in the data array
});
And we pass this third element (d[2]) to the function generate as a parameter named thisWords:
function generate(thisWords){
d3.layout.cloud().size([800, 300])
.words(thisWords)
.rotate(0)
.fontSize(function(d) { return d.size; })
.on("end", draw)
.start();
}
here is your fiddle: https://jsfiddle.net/jwrbps4j/
PS: you'll have to improve the translate for that words.

Make Hierarchical Bar Chart Vertical

I'm trying to create a vertical hierarchial bar chart based on this example http://bl.ocks.org/mbostock/1283663 .
I was able to position the axes but I can't seem to move the bars to start from the bottom of the chart rather than the top. Can anyone help?
var margin = {top: 30, right: 120, bottom: 30, left: 120},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var y = d3.scale.linear()
.range([height,0]);
var barWidth = 20;
var color = d3.scale.ordinal()
.range(["steelblue", "#ccc"]);
var duration = 750,
delay = 25;
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var xAxis = d3.svg.axis()
.scale(barWidth)
.orient("botom");
var svg = d3.select(".sales-pipeline-chart").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", up);
svg.append("g")
.attr("class", "y axis");
svg.append("g")
.attr("class", "x axis")
.append("line")
.attr("x1", "100%")
.attr("transform", "translate(0," + height + ")");
d3.json("/flare.json", function(root) {
partition.nodes(root);
y.domain([0, root.value]).nice();
down(root, 0);
});
function down(d, i) {
if (!d.children || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
var enter = bar(d)
.attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", color(true));
// Update the x-scale domain.
y.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", function(d, i) { return "translate(" + barWidth *
i * 1.2 + ",0)"; });
// Transition entering text.
enterTransition.select("text")
.style("fill-opacity", 1);
// Transition entering rects to the new x-scale.
enterTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.style("fill", function(d) { return color(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new x-scale.
exitTransition.selectAll("rect")
.attr("height", function(d) { return y(d.value); });
// Rebind the current node to the background.
svg.select(".background")
.datum(d)
.transition()
.duration(end);
d.index = i;
}
function up(d) {
if (!d.parent || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", function(d, i) { return "translate(" + barWidth *
i * 1.2 + ",0)"; })
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function(d) { return color(!!d.children); })
.filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Update the x-scale domain.
y.domain([0, d3.max(d.parent.children, function(d) { return d.value;
})]).nice();
// Update the x-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new x-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.each("end", function(p) { if (p === d)
d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition()
.duration(end)
.remove();
// Rebind the current parent to the background.
svg.select(".background")
.datum(d.parent)
.transition()
.duration(end);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("g", ".x.axis")
.attr("class", "enter")
.attr("transform", "translate(5,0)")
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", function(d) { return !d.children ? null : "pointer";
})
.on("click", down);
bar.append("text")
.attr("y", -6)
.attr("x", barWidth / 2)
.attr("dx", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.name; });
bar.append("rect")
.attr("height", function(d) { return y(d.value); })
.attr("width", barWidth);
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var y0 = 0;
return function(d) {
var tx = "translate(" + barWidth * i * 1.2 + "," + y0 + ")";
y0 += y(d.value);
return tx;
};
}
I was able to move the bars so they now start at the bottom but there are still some problems with the animation. The drill up doesn't work and also I would like to move the text below the xAxis.
var margin = {top: 30, right: 120, bottom: 30, left: 120},
width = 600 - margin.left - margin.right,
height = 300 - margin.top - margin.bottom;
var y = d3.scale.linear()
.range([height,0]);
var barHeight = 40;
var color = d3.scale.ordinal()
.range(["steelblue", "#ccc"]);
var duration = 750,
delay = 25;
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var xAxis = d3.svg.axis()
.scale(barHeight)
.orient("botom");
var svg = d3.select(".sales-pipeline-chart").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.right + "," + margin.top + ")");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", up);
svg.append("g")
.attr("class", "y axis");
svg.append("g")
.attr("class", "x axis")
.append("line")
.attr("x1", "100%")
.attr("transform", "translate(0," + height + ")");
d3.json("/flare.json", function(root) {
partition.nodes(root);
y.domain([0, root.value]).nice();
down(root, 0);
});
function down(d, i) {
if (!d.children || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter").attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
//var barHeight = w / d.children.length;
var enter = bar(d)
.attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", color(true));
// Update the y-scale domain.
y.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();
// Update the y-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", function(d, i) { return "translate(" + barHeight * i * 1.2 + "," + (height- y(d.value)) + ")"; });
// Transition entering text.
enterTransition.select("text").style("fill-opacity", 1);
// Transition entering rects to the new x-scale.
enterTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.style("fill", function(d) { return color(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new x-scale.
exitTransition.selectAll("rect").attr("height", function(d) { return y(d.value); });
// Rebind the current node to the background.
svg.select(".background").data(d).transition().duration(duration * 2); d.index = i;
}
function up(d) {
if (!d.parent || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter").attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", function(d, i) { return "translate(" + barHeight * i * 1.2 + "," + (height - y(d.value)) + ")"; })
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function(d) { return color(!!d.children); })
.filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Update the x-scale domain.
y.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new x-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition().duration(end).remove();
// Rebind the current parent to the background.
svg.select(".background").data(d.parent).transition().duration(duration * 2);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("g", ".x.axis")
.attr("class", "enter")
.attr("transform", "translate(10,0)")//0.10
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", function(d) { return !d.children ? null : "pointer"; })
.on("click", down);
bar.append("text")
.attr("y", -6)
.attr("x",barHeight/2)
.attr("dx", ".35em")//
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
bar.append("rect")
.attr("height", function(d) { return y(d.value); })
.attr("width", barHeight);
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var y0 = 0;
return function(d) {
var ty = "translate(" + barHeight * i * 1.2+ "," + y0 + ")";
y0 += y(d.value);
return ty;
};
}

D3 hierarchical bar chart - Rotate X and Y Axes

I saw an example of a hierarchical bar chart and got it working for my dataset also.
http://d3-example.herokuapp.com/examples/bar/bar-hierarchy.html
However, I would like to have the x and Y axes switched. Basically, would like to see a vertical Bar Chart with hierarchical data. Please Help!
Cheers,
Arjun
here i have solved your issue kindly review my
code
and you will get the solution.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
text {
font: 10px sans-serif;
}
rect.background {
fill: white;
}
.axis {
shape-rendering: crispEdges;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
}
</style>
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 10, right: 120, bottom: 120, left: 120},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var y = d3.scale.linear()
.range([height, 0]);
var barHeight = 20;
var color = d3.scale.ordinal()
.range(["steelblue", "#ccc"]);
var duration = 750,
delay = 25;
var partition = d3.layout.partition()
.value(function(d) { return d.size; });
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg.append("rect")
.attr("class", "background")
.attr("width", width)
.attr("height", height)
.on("click", up);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0, " + height + ")")
.append("line")
.attr("x1", "100%");
svg.append("g")
.attr("class", "y axis");
d3.json("https://jsonblob.com/api/f577d19c-0f2b-11e7-a0ba-09040711ce47", function(error, root) {
if (error) throw error;
partition.nodes(root);
y.domain([0, root.value]).nice();
down(root, 0);
});
function down(d, i) {
if (!d.children || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
var enter = bar(d)
.attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", color(true));
// Update the x-scale domain.
y.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", function(d, i) { return "translate(" + barHeight * i * 2.5 + "," + 0 + ")"; });
// Transition entering text.
enterTransition.select("text")
.style("fill-opacity", 1);
// Transition entering rects to the new y-scale.
enterTransition.select("rect")
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.style("fill", function(d) { return color(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new y-scale.
exitTransition.selectAll("rect")
.attr("height", function(d) { return height - y(d.value); });
// Rebind the current node to the background.
svg.select(".background")
.datum(d)
.transition()
.duration(end);
d.index = i;
}
function up(d) {
if (!d.parent || this.__transition__) return;
var end = duration + d.children.length * delay;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter")
.attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", function(d, i) { return "translate(" + barHeight * i * 2.5 + "," + 0 + ")"; })
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function(d) { return color(!!d.children); })
.filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Update the y-scale domain.
y.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();
// Update the y-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(end)
.style("opacity", 1);
// Transition entering rects to the new y-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("height", function(d) { return height - y(d.value); })
.attr("y", function(d) { return y(d.value); })
.each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("height", function(d) { return height - y(d.value); })
.attr("y", function(d) { return y(d.value); })
.style("fill", color(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition()
.duration(end)
.remove();
// Rebind the current parent to the background.
svg.select(".background")
.datum(d.parent)
.transition()
.duration(end);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("g", ".x.axis")
.attr("class", "enter")
.attr("transform", "translate(15,0)")
.selectAll("g")
.data(d.children)
.enter().append("g")
.style("cursor", function(d) { return !d.children ? null : "pointer"; })
.on("click", down);
bar.append("text")
.attr("x", barHeight / 2)
.attr("y", height + 10)
.attr("dy", ".35em")
.style("text-anchor", "start")
.text(function(d) { return d.name; })
.attr("transform", "rotate(45 " + (barHeight / 2) + " " + (height + 10) + ")")
bar.append("rect")
.attr("width", barHeight)
.attr("height", function(d) { return height - y(d.value); })
.attr("y", function(d) { return y(d.value); });
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var y0 = 0;
return function(d) {
var tx = "translate(" + barHeight * i * 1.5 + "," + y0 + ")";
y0 += y(d.value);
return tx;
};
}
</script>
This isn't quite right.. but it's half way there.. the animations don't really work as nicely as the horizontal bar and the drill up completely doesn't work.. hoping someone can help add to it..
var m = [40, 50, 5, 70], // top right bottom left
w = 550 - m[1] - m[3], // width
h = 384 - m[0] - m[2], // height
y = d3.scale.linear().range([h,0]),
x = 70, // bar width
z = d3.scale.ordinal().range(["steelblue", "#aaa"]); // bar color
var hierarchy = d3.layout.partition()
.value(function(d) { return d.size; });
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var svg = d3.select(".sales-pipeline-chart").append("svg:svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.append("svg:g")
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");
svg.append("svg:rect")
.attr("class", "background")
.attr("width", w)
.attr("height", h)
.on("click", up);
svg.append("svg:g")
.attr("class", "x axis");
svg.append("svg:g")
.attr("class", "y axis");
/*.append("svg:line")
.attr("y1", "100%");*/
d3.json("/flare.json", function(root) {
hierarchy.nodes(root);
y.domain([0,root.value]).nice();
down(root, 0);
});
function down(d, i) {
if (!d.children || this.__transition__) return;
var duration = d3.event && d3.event.altKey ? 7500 : 750,
delay = duration / d.children.length;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter").attr("class", "exit");
// Entering nodes immediately obscure the clicked-on bar, so hide it.
exit.selectAll("rect").filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Enter the new bars for the clicked-on data.
// Per above, entering bars are immediately visible.
//var barWidth = w / d.children.length;
var enter = bar(d)
.attr("transform", stack(i))
.style("opacity", 1);
// Have the text fade-in, even though the bars are visible.
// Color the bars as parents; they will fade to children if appropriate.
enter.select("text").style("fill-opacity", 1e-6);
enter.select("rect").style("fill", z(true));
// Update the y-scale domain.
y.domain([0, d3.max(d.children, function(d) { return d.value; })]).nice();
// Update the y-axis.
svg.selectAll(".y.axis").transition()
.duration(duration)
.call(yAxis);
// Transition entering bars to their new position.
var enterTransition = enter.transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", function(d, i) { return "translate(" + x * i * 1.3 + "," + (h - y(d.value)) + ")"; });
/*.call(xAxis);*/
// Transition entering text.
enterTransition.select("text").style("fill-opacity", 1);
// Transition entering rects to the new x-scale.
enterTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.style("fill", function(d) { return z(!!d.children); });
// Transition exiting bars to fade out.
var exitTransition = exit.transition()
.duration(duration)
.style("opacity", 1e-6)
.remove();
// Transition exiting bars to the new x-scale.
exitTransition.selectAll("rect").attr("height", function(d) { return y(d.value); });
// Rebind the current node to the background.
svg.select(".background").data([d]).transition().duration(duration * 2); d.index = i;
}
function up(d) {
if (!d.parent || this.__transition__) return;
var duration = d3.event && d3.event.altKey ? 7500 : 750,
delay = duration / d.children.length;
// Mark any currently-displayed bars as exiting.
var exit = svg.selectAll(".enter").attr("class", "exit");
// Enter the new bars for the clicked-on data's parent.
var enter = bar(d.parent)
.attr("transform", function(d, i) { return "translate(" + x * i * 1.3 + "," + (h - y(d.value)) + ")"; })
.style("opacity", 1e-6);
// Color the bars as appropriate.
// Exiting nodes will obscure the parent bar, so hide it.
enter.select("rect")
.style("fill", function(d) { return z(!!d.children); })
.filter(function(p) { return p === d; })
.style("fill-opacity", 1e-6);
// Update the x-scale domain.
y.domain([0, d3.max(d.parent.children, function(d) { return d.value; })]).nice();
// Update the x-axis.
svg.selectAll(".y.axis").transition()
.duration(duration * 2)
.call(yAxis);
// Transition entering bars to fade in over the full duration.
var enterTransition = enter.transition()
.duration(duration * 2)
.style("opacity", 1);
// Transition entering rects to the new x-scale.
// When the entering parent rect is done, make it visible!
enterTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.each("end", function(p) { if (p === d) d3.select(this).style("fill-opacity", null); });
// Transition exiting bars to the parent's position.
var exitTransition = exit.selectAll("g").transition()
.duration(duration)
.delay(function(d, i) { return i * delay; })
.attr("transform", stack(d.index));
// Transition exiting text to fade out.
exitTransition.select("text")
.style("fill-opacity", 1e-6);
// Transition exiting rects to the new scale and fade to parent color.
exitTransition.select("rect")
.attr("height", function(d) { return y(d.value); })
.style("fill", z(true));
// Remove exiting nodes when the last child has finished transitioning.
exit.transition().duration(duration * 2).remove();
// Rebind the current parent to the background.
svg.select(".background").data([d.parent]).transition().duration(duration * 2);
}
// Creates a set of bars for the given data node, at the specified index.
function bar(d) {
var bar = svg.insert("svg:g", ".x.axis")
.attr("class", "enter")
.attr("transform", "translate(10,0)")
.selectAll("g")
.data(d.children)
.enter().append("svg:g")
.style("cursor", function(d) { return !d.children ? null : "pointer"; })
.on("click", down);
bar.append("svg:text")
.attr("y", -6)
.attr("x", x / 2)
//.attr("dx", ".35em")
.attr("text-anchor", "end")
.text(function(d) { return d.name; });
/*var barWidth = w / d.children.length;*/
bar.append("svg:rect")
.attr("height", function(d) { return y(d.value); })
.attr("width", x/*barWidth*/);
return bar;
}
// A stateful closure for stacking bars horizontally.
function stack(i) {
var y0 = 0;
return function(d) {
var ty = "translate(" + x * i * 1.2 + "," + y0 + ")";
y0 += y(d.value);
return ty;
};
}

How do you make an SVG element mouse event bubble up through another element?

I have a D3 line chart where I'm placing a rect 'behind' the chart. This rect has a mouse event attached to it, but the problem is my chart also has another rect overlaid 'above' the chart that also has events attached to it.
How do I get the lower rect mouse events to bubble up above the higher rect that is overlayed on top? Thanks so much!
I've created a Fiddle here:
http://jsfiddle.net/TnjCC/1/
And here is my code. Look for the "This is where I need the mouseover to bubble up" comment to see which element I'd like to bubble up.
var data = [
{"date":"1-May-13","close":58.13},
{"date":"30-Apr-13","close":53.98},
{"date":"27-Apr-13","close":67.00},
{"date":"26-Apr-13","close":89.70},
{"date":"25-Apr-13","close":99.00},
{"date":"24-Apr-13","close":130.28},
{"date":"23-Apr-13","close":166.70},
{"date":"20-Apr-13","close":234.98},
{"date":"19-Apr-13","close":345.44},
{"date":"18-Apr-13","close":443.34},
];
var margin = {top: 20, right: 50, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse,
bisectDate = d3.bisector(function(d) { return d.date; }).left,
formatValue = d3.format(",.2f"),
formatCurrency = function(d) { return "$" + formatValue(d); };
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
data.sort(function(a, b) {
return a.date - b.date;
});
x.domain([data[0].date, data[data.length - 1].date]);
y.domain(d3.extent(data, function(d) { return d.close; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Price ($)");
<!-- This is where I need the mouseover to bubble up -->
var left = x(new Date("Apr 23 2013"));
var right = x(new Date("Apr 26 2013"));
var wid = right - left;
svg.append("rect")
.attr("id", "range")
.attr("class", "range")
.attr("x", left)
.attr("width", wid)
.attr("height", height)
.on("mouseover", function () {
alert("I can see you!");
})
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");
focus.append("circle")
.attr("r", 4.5);
focus.append("text")
.attr("x", 9)
.attr("dy", ".35em");
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
function mousemove() {
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
focus.attr("transform", "translate(" + x(d.date) + "," + y(d.close) + ")");
focus.select("text").text(formatCurrency(d.close));
}
});
You can also use the following style, to "hide" certain svg elements for mouse events. In my case, it was the mouseover event, that I wanted to bubble through:
pointer-events: none;
For a quick fix, you can move the range above the overlay and manually call the overlay event handlers from the range.
http://jsfiddle.net/Rk5Hp/
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
// move range above overlay and call the overlay event handlers from there
svg.append("rect")
.attr("id", "range")
.attr("class", "range")
.attr("x", left)
.attr("width", wid)
.attr("height", height)
.on("mousemove", mousemove)
.on("mouseout", function() { focus.style("display", "none"); })
.on("mouseover", function() {
focus.style("display", null);
// event handling for range mouseover (alert broke mouse move)
console.log("I can see you!");
});
Bubbling acts at the dom level, and since there is no way to have a rect be a child of another rect, bubbling will not take care of this for you. Grouping the elements together and placing a handler that checks the event target on the group will keep you from registering the event handler twice, but suffers from the same basic problem: when elements overlap, whichever element is declared last in the source order will get the event.
All above answers are right but I wanted to give another example:
let log = console.log
let data = []
let pointStart = document.querySelector("svg").createSVGPoint()
let pointStop = document.querySelector("svg").createSVGPoint()
let divLog = d3.select("#log")
var svg = d3.select("svg")
var linearfn = d3.line()
.x(d => d.x)
.y(d => d.y)
.curve(d3.curveLinear)
function logTagName(eventName, tagName) {
divLog.html(divLog.html() + eventName + " : " + tagName + "<br/>")
}
svg.on("click", function() {
log("tagName: ", event.target.tagName)
logTagName("svg click", event.target.tagName)
pointStart.x = event.x - 8
pointStart.y = event.y - 8
data.push({
x: pointStart.x,
y: pointStart.y
})
svg.selectAll("path") // SVG içinde tanımlı path elemanlarını bul
.data([1]).enter() // 1 elemanlı dizinin eleman sayısı kadarı için enter()
.append('path') // dizi elemanı kadar path oluştur
.attr("fill", "none")
.attr("stroke", "black")
.attr("stroke-width", 8)
.attr("d", linearfn(data))
.on("click", function() {
log("tagName: ", event.target.tagName)
logTagName("path click", event.target.tagName)
/* click event will start from path and pass to the svg element */
// event.stopPropagation(); // letting pass event bubbling
})
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", d => d.x + .5)
.attr("cy", d => d.y + .5)
.attr("r", 20)
.attr("stroke-width", 3)
.attr("stroke", "red")
.attr("cursor", "move")
.style("fill", "transparent")
.attr("pointer-events", "all") // when clicked in/outside of circle, it'll handle events
.on("mouseover", function() {
log("over oldu")
d3.select(this).style("stroke", "blue");
})
.on("mouseout", function() {
log("out oldu")
d3.select(this).style("stroke", "red");
})
.on("click", function() {
event.stopPropagation(); // not letting pass event bubbling
event.preventDefault();
log("click oldu")
d3.select(this).style("stroke", "black");
})
})
.on("mousemove", function() {
// fare hareketinde de çizdireceğiz ama x,y noktasını
// tıklanıncaya kadar diziye eklemeyeceğiz
pointStop.x = event.x - 8
pointStop.y = event.y - 8
svg.select("path")
.attr("d", linearfn(data.concat({
x: pointStop.x,
y: pointStop.y
})))
})
https://jsfiddle.net/jsfiddleCem/hnsu68jw/

Categories