Unable to position tooltip on d3js bar chart - javascript

I've a bar chart using d3. When I hover over a bar I'm showing a tooltip. Whenever I've different set of data(number of bars), I'm unable to position the tooltip pointer to the center of the bar on the bar-chart. I need the pointer to be at the center of the bar for any number of bars on the chart. I'm using the x-axis values but, the tooltip is not placing at the right position.
Following is the snippet for the same
var width = 216;
var height = 200;
var barPadding = 18;
var barWidth = 58;
var dataSize = d3.selectAll(dataset).size();
var margin = {
top: 10,
right: 0,
bottom: 58,
left: 30
};
var width_box_sizing_border_box = width + margin.left + margin.right;
var height_box_sizing_border_box = height + margin.bottom + margin.top;
var graph;
var xScale;
var yScale;
var dataset;
var xTicks = 6;
var yTicks = 6;
var tooltipEl = function(d) {
return (
'<div>' + d.val + '</div>'
)
}
dataset = [{
desc: 'test1',
val: 40
}, {
desc: 'some dummy text here',
val: 120
}];
xScale = d3.scaleBand()
.domain(dataset.map(function(d) {
return d.desc;
}))
.range([margin.left, width - margin.right]);
yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, 350]);
graph = d3.select("#graph")
.append("svg")
.attr("class", "bar-chart")
.attr("width", width_box_sizing_border_box)
.attr("height", height_box_sizing_border_box);
// Tool Tip
const div = d3
.select('#graph')
.append('div')
.attr('class', 'tooltip')
.style('opacity', 0);
graph.append("g")
.attr("class", "x-scale")
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(xScale).ticks(xTicks))
.selectAll(".tick text")
.call(wrap, xScale.bandwidth());
graph.append("g")
.attr("class", "y-scale")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(yScale).ticks(yTicks).tickPadding(10));
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth() / 2 - (barWidth - barPadding) / 2) + "," + margin.top + ")")
.attr('class', 'graph-placeholder')
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar1")
.attr("height", height)
.attr("width", barWidth - barPadding)
.attr('x', d => xScale(d.desc));
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth() / 2 - (barWidth - barPadding) / 2) + "," + margin.top + ")")
.attr('class', 'graph-main')
.selectAll("bar1")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar2")
.attr('x', d => xScale(d.desc))
.attr("y", function(d) {
return yScale(d.val);
})
.attr("height", function(d) {
return height - yScale(d.val);
})
.attr("width", barWidth - barPadding)
.on('mouseover', d => {
div
.html(tooltipEl(d));
div
.transition()
.duration(200)
.style('display', 'block')
.style('opacity', 1);
div
.style('left', xScale(d.desc) + 'px')
.style('top', (height + margin.top + 8) + 'px');
})
.on('mouseout', () => {
div
.transition()
.duration(500)
.style('opacity', 0)
.style('display', 'none')
});
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth() / 2 - (barWidth - barPadding) / 2) + "," + margin.top + ")")
.attr('class', 'bar-label')
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d.val + '%')
.attr("y", function(d) {
return yScale(d.val) - 5;
}).attr('x', function(d) {
return xScale(d.desc) + ((barWidth - barPadding) / 2 - d3.select(this).node().getBBox().width / 2);
});
function wrap(text, width) {
text.each(function() {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
.bar-chart {
background-color: #ccc;
}
.bar2 {
fill: steelblue;
}
.bar1 {
fill: #f2f2f2;
}
text {
font-size: 12px;
text-anchor: middle;
}
.bar-label text {
text-anchor: start;
}
path.domain {
stroke-width: 0;
display: none;
}
.tooltip {
background: #FFFFFF;
box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.33);
font-family: "Segoe UI";
line-height: normal;
padding: 15px;
width: 400px;
position: absolute;
display: none;
}
.tooltip__container {
display: flex;
}
.tooltip::before {
content: "";
position: absolute;
left: 22px;
top: -8px;
transition: all 0.5s ease;
border: 8px solid #fff;
box-shadow: -5px -5px 5px rgba(0, 0, 0, 0.1);
transform: rotate(45deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
<div id="graph"></div>
</div>
Fiddle

-- Edited
This should be generic enough. Tested it with between 2 to 8 bars and seems on point.
.on('mouseover', d => {
div
.html(tooltipEl(d));
div
.transition()
.duration(200)
.style('display', 'block')
.style('opacity', 1);
div
.style('left', xScale(d.desc) + (xScale.bandwidth() / 2 - (barWidth - barPadding) / 2) - 1 + 'px')
.style('top', (height + margin.top + 8) + 'px');
})

Related

Bar position in d3 is not matching with axis

I've a bar chart made using d3js where I'm unable to position the bars properly along the x-axis. The bars are not positioned relative to the axis tics.
Following is the snippet for the same.
var width = 216;
var height = 200;
var barPadding = 18;
var barWidth = 58;
var dataSize = d3.selectAll(dataset).size();
var margin = { top: 10, right: 0, bottom: 58, left: 30 };
var width_box_sizing_border_box = width + margin.left + margin.right;
var height_box_sizing_border_box = height + margin.bottom + margin.top;
//var start = (width - margin.left - margin.right - (dataSize * barWidth) + barPadding) / 2;
var graph;
var xScale;
var yScale;
var dataset;
var xTicks = 6;
var yTicks = 6;
dataset = [{ desc: 'test1', val: 40 }, { desc: 'some dummy text here', val: 120 }];
xScale = d3.scaleBand()
.domain(dataset.map(function (d) {
return d.desc;
}))
.range([margin.left, width-margin.right]);
yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, 350]);
graph = d3.select("#graph")
.append("svg")
.attr("class", "bar-chart")
.attr("width", width_box_sizing_border_box)
.attr("height", height_box_sizing_border_box)
graph.append("g")
.attr("class", "x-scale")
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(xScale).ticks(xTicks))
.selectAll(".tick text")
.call(wrap, xScale.bandwidth());
graph.append("g")
.attr("class", "y-scale")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(yScale).ticks(yTicks).tickPadding(10));
graph
.append("g")
.attr("transform", "translate(0," + margin.top + ")")
.attr('class', 'graph-placeholder')
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar1")
.attr("height", height)
.attr("width", barWidth - barPadding)
.attr('x', d => xScale(d.desc));
graph
.append("g")
.attr("transform", "translate(0," + margin.top + ")")
.attr('class', 'graph-main')
.selectAll("bar1")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar2")
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val);
})
.attr("height", function (d) {
return height - yScale(d.val);
})
.attr("width", barWidth - barPadding);
graph
.append("g")
.attr("transform", "translate(0," + margin.top + ")")
.attr('class', 'bar-label')
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d.val + '%')
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val) - 5;
})
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
.bar-chart {
background-color: #ccc;
}
.bar2 {
fill: steelblue;
}
.bar1 {
fill: #f2f2f2;
}
text {
font-size: 12px;
text-anchor: middle;
}
.bar-label text {
text-anchor: start;
}
path.domain {
stroke-width: 0;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
<div id="graph"></div>
</div>
Here's how you can compute the center point to place the bars/texts
Bars and texts:
xScale.bandwidth()/2 - barWidth/2
Additional offset for the texts to center them within the bars:
Once the text attribute is assigned, position the text (i.e. x) based on the barWidth and this particular text width.
In short terms: barWidth/2 - textWidth/2 and to do that you can use the getBBox method. Here's how:
.attr('x', function (d) {
return xScale(d.desc) + ((barWidth - barPadding)/2 - d3.select(this).node().getBBox().width/2);
});
Applying the above 2 changes to your chart, here's a fork of your fiddle (and an inline snippet)
var width = 216;
var height = 200;
var barPadding = 18;
var barWidth = 58;
var dataSize = d3.selectAll(dataset).size();
var margin = { top: 10, right: 0, bottom: 58, left: 30 };
var width_box_sizing_border_box = width + margin.left + margin.right;
var height_box_sizing_border_box = height + margin.bottom + margin.top;
//var start = (width - margin.left - margin.right - (dataSize * barWidth) + barPadding) / 2;
var graph;
var xScale;
var yScale;
var dataset;
var xTicks = 6;
var yTicks = 6;
dataset = [{ desc: 'test1', val: 40 }, { desc: 'some dummy text here', val: 120 }];
xScale = d3.scaleBand()
.domain(dataset.map(function (d) {
return d.desc;
}))
.range([margin.left, width-margin.right]);
yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, 350]);
graph = d3.select("#graph")
.append("svg")
.attr("class", "bar-chart")
.attr("width", width_box_sizing_border_box)
.attr("height", height_box_sizing_border_box)
graph.append("g")
.attr("class", "x-scale")
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(xScale).ticks(xTicks))
.selectAll(".tick text")
.call(wrap, xScale.bandwidth());
graph.append("g")
.attr("class", "y-scale")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(yScale).ticks(yTicks).tickPadding(10));
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth()/2 - (barWidth - barPadding)/2) + "," + margin.top + ")")
.attr('class', 'graph-placeholder')
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar1")
.attr("height", height)
.attr("width", barWidth - barPadding)
.attr('x', d => xScale(d.desc));
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth()/2 - (barWidth - barPadding)/2) + "," + margin.top + ")")
.attr('class', 'graph-main')
.selectAll("bar1")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar2")
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val);
})
.attr("height", function (d) {
return height - yScale(d.val);
})
.attr("width", barWidth - barPadding);
graph
.append("g")
.attr("transform", "translate(" + (xScale.bandwidth()/2 - (barWidth - barPadding)/2) + "," + margin.top + ")")
.attr('class', 'bar-label')
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d.val + '%')
.attr("y", function (d) {
return yScale(d.val) - 5;
}).attr('x', function (d) {
return xScale(d.desc) + ((barWidth - barPadding)/2 - d3.select(this).node().getBBox().width/2);
});
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
.bar-chart {
background-color: #ccc;
}
.bar2 {
fill: steelblue;
}
.bar1 {
fill: #f2f2f2;
}
text {
font-size: 12px;
text-anchor: middle;
}
.bar-label text {
text-anchor: start;
}
path.domain {
stroke-width: 0;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
<div id="graph"></div>
</div>
Fiddle link: http://jsfiddle.net/xsuL8q4j/
Hope this helps.
Updated
You need to changed translate as per your need see demo
var width = 216;
var height = 200;
var barPadding = 18;
var barWidth = 58;
var dataSize = d3.selectAll(dataset).size();
var margin = { top: 10, right: 0, bottom: 58, left: 30 };
var width_box_sizing_border_box = width + margin.left + margin.right;
var height_box_sizing_border_box = height + margin.bottom + margin.top;
//var start = (width - margin.left - margin.right - (dataSize * barWidth) + barPadding) / 2;
var graph;
var xScale;
var yScale;
var dataset;
var xTicks = 6;
var yTicks = 6;
dataset = [{ desc: 'test1', val: 40 }, { desc: 'some dummy text here', val: 120 }];
xScale = d3.scaleBand()
.domain(dataset.map(function (d) {
return d.desc;
}))
.range([margin.left, width-margin.right]);
yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, 350]);
graph = d3.select("#graph")
.append("svg")
.attr("class", "bar-chart")
.attr("width", width_box_sizing_border_box)
.attr("height", height_box_sizing_border_box)
graph.append("g")
.attr("class", "x-scale")
// changed translate here as per your need
.attr("transform", "translate(0," + (height + margin.top) + ")")
.call(d3.axisBottom(xScale).ticks(xTicks))
.selectAll(".tick text")
.call(wrap, xScale.bandwidth());
graph.append("g")
.attr("class", "y-scale")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(yScale).ticks(yTicks).tickPadding(10));
graph
.append("g")
.attr("transform", "translate(30," + margin.top + ")")
.attr('class', 'graph-placeholder')
.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar1")
.attr("height", height)
.attr("width", barWidth - barPadding)
.attr('x', d => xScale(d.desc));
graph
.append("g")
.attr("transform", "translate(30," + margin.top + ")")
.attr('class', 'graph-main')
.selectAll("bar1")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bar2")
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val);
})
.attr("height", function (d) {
return height - yScale(d.val);
})
.attr("width", barWidth - barPadding);
graph
.append("g")
.attr("transform", "translate(35," + margin.top + ")")
.attr('class', 'bar-label')
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(d => d.val + '%')
.attr('x', d => xScale(d.desc))
.attr("y", function (d) {
return yScale(d.val) - 5;
})
function wrap(text, width) {
text.each(function () {
var text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1,
y = text.attr("y"),
dy = parseFloat(text.attr("dy")),
tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
while (word = words.pop()) {
line.push(word);
tspan.text(line.join(" "));
if (tspan.node().getComputedTextLength() > width) {
line.pop();
tspan.text(line.join(" "));
line = [word];
tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
.bar-chart {
background-color: #ccc;
}
.bar2 {
fill: steelblue;
}
.bar1 {
fill: #f2f2f2;
}
text {
font-size: 12px;
text-anchor: middle;
}
.bar-label text {
text-anchor: start;
}
path.domain {
stroke-width: 0;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div class="container">
<div id="graph"></div>
</div>

Positioning of canvas after the conversion from D3

I just managed to convert the respective heatmap from SVG to canvas. (due to large dataset vs performance issue) However the position of the generated heatmap has goes to a new region. I not sure how am I going to do about this. By changing the transform does not change anything as well.
My code:
var units = [];
for(var unit_i = 0; unit_i<=101;){
if(unit_i==0){
units.push(1);
unit_i = unit_i + 5;
}
else{
units.push(unit_i);
unit_i = unit_i + 4;
}
}
var times = [];
for(var times_i = 0; times_i<=1440;){
if(times_i==0){
times.push(1);
times_i = times_i + 10;
}
else{
times.push(times_i);
times_i = times_i + 9;
}
}
var newSample = [{unit:null, timestamp: null, level: null}];
//by using below method we can observe the delay is not due to the data during insertion
for(var unit=1; unit<=99; unit++){
for(var timestamp = 1; timestamp<=100; timestamp++){
var i = Math.random() * 1400;
newSample.push({unit:unit, timestamp: timestamp, level:i});
}
}
var hours = 0;
var hoursIndicator = 0;
var margin = {
top: 170,
right: 100,
bottom: 70,
left: 100
};
var width = 2500,//optimized width
//gridSize = Math.floor(width / times.length),//optimized gridsize
gridSize = 10;//if 20 each interval will have 5
height = 50 * (units.length); //optimized, the greater the length, the greater the height
console.log("this is gridSize:" + gridSize +", this is height: " + height + ", and this is width: " + width);
//SVG container
var svg = d3.select('.trafficCongestions')
.append("svg")
//.style("position", "absolute")
.attr("width", width + margin.left + margin.right)//optimization
.attr("height", height + margin.top + margin.bottom)//optimization
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var canvas = d3.select('.trafficCongestions').append("canvas")
.attr("id", "canvas")
.attr("width", width + margin.left + margin.right)//optimization
.attr("height", height + margin.top + margin.bottom);//optimization
var context = canvas.node().getContext("2d");
context.clearRect(0, 0, width, height);
var detachedContainer = document.createElement("custom");
var dataContainer = d3.select(detachedContainer);
//Reset the overall font size
var newFontSize = width * 62.5 / 900;
//heatmap drawing starts from here
var colorScale = d3.scaleLinear()
.domain([0, d3.max(newSample, function(d, i) {return d.level; })/2, d3.max(newSample, function(d, i) {return d.level; })])
.range(["#009933", "#FFCC00", "#990000"])//obtain the max data value of count
//y-axis (solely based on data of days)
var dayLabels = svg.selectAll(".dayLabel")
.data(units)
.enter().append("text")
.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) {
return (i) * (gridSize * 4)/*adjusts the interval distance with (n - 1) concept*/; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize + ")");
//x-axis (solely based on data of times)
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter().append("text")
.text(function(d, i) {
var hrs = Math.floor(d/60);
var mins = d%60;
if(hrs<10){
if(mins<10){
return "0"+hrs + ":0" + mins;
}
return "0"+ hrs + ":" + mins;
}
return hrs +":"+ mins;
})
.attr("x", function(d, i) { return i * (gridSize * 9)/*adjusts the interval distance with (n - 1) concept*/; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + 1 + ", -6)")
var heatMap = dataContainer.selectAll("custom.rect")
.data(newSample)
.enter().append("custom")
.attr("x", function(d) {
return (d.timestamp - 1) * (gridSize);
})
.attr("y", function(d) {
console.log(d.unit);
return (d.unit - 1) * (gridSize);
})
.classed("rect", true)
.attr("class", " rect bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.attr("strokeStyle", "rgba(255,255,255, 0.6)")//to have the middle line or not
.attr("fillStyle", function(d,i){
return colorScale(d.level);
});
drawCanvas();
//Append title to the top
svg.append("text")
.attr("class", "title")
.attr("x", width/2)
.attr("y", -90)
.style("text-anchor", "middle")
.text("Sample Result");
svg.append("text")
.attr("class", "subtitle")
.attr("x", width/2)
.attr("y", -60)
.style("text-anchor", "middle")
.text("HEATMAP");
//Append credit at bottom
svg.append("text")
.attr("class", "credit")
.attr("x", width/2)
.attr("y", gridSize * (units.length+1) + 80)
.style("text-anchor", "middle");
//Extra scale since the color scale is interpolated
var countScale = d3.scaleLinear()
.domain([0, d3.max(newSample, function(d) {return d.level; })])
.range([0, width])
//Calculate the variables for the temp gradient
var numStops = 10;
countRange = countScale.domain();
countRange[2] = countRange[1] - countRange[0];
countPoint = [];
for(var i = 0; i < numStops; i++) {
countPoint.push(i * countRange[2]/(numStops-1) + countRange[0]);
}//for i
//Create the gradient
svg.append("defs")
.append("linearGradient")
.attr("id", "legendLevel")
.attr("x1", "0%").attr("y1", "0%")
.attr("x2", "100%").attr("y2", "0%")
.selectAll("stop")
.data(d3.range(numStops))
.enter().append("stop")
.attr("offset", function(d,i) {
return countScale( countPoint[i] )/width;
})
.attr("stop-color", function(d,i) {
return colorScale( countPoint[i] );
});
var legendWidth = Math.min(width, 400);//the width of the legend
console.log(width);
//Color Legend container
var legendsvg = svg.append("g")
.attr("class", "legendWrapper")
.attr("transform", "translate(" + (width/2) + "," + (gridSize * 100 + 40) + ")");
//Draw the Rectangle
legendsvg.append("rect")
.attr("class", "legendRect")
.attr("x", -legendWidth/2)
.attr("y", 0)
.attr("width", legendWidth)
.attr("height", 10)
.style("fill", "url(#legendLevel)");
//Append title
legendsvg.append("text")
.attr("class", "legendTitle")
.attr("x", 0)
.attr("y", -10)
.style("text-anchor", "middle")
.text("Level");
//Set scale for x-axis
var xScale = d3.scaleLinear()
.range([-legendWidth/2, legendWidth/2])
.domain([ 0, d3.max(newSample, function(d) { return d.level; })] );
//Define x-axis
var xAxis = d3.axisBottom()
.ticks(5)
.scale(xScale);
//Set up X axis
legendsvg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (10) + ")")
.call(xAxis);
function drawCanvas(){
var elements = dataContainer.selectAll("custom.rect");
elements.each(function(d){
var node = d3.select(this);
context.beginPath();
context.fillStyle = node.attr("fillStyle");
context.rect(node.attr("x"), node.attr("y"), node.attr("width"), node.attr("height"));
context.fill();
context.closePath();
});
}
html { font-size: 100%; }
.timeLabel, .dayLabel {
font-size: 1rem;
fill: #AAAAAA;
font-weight: 300;
}
.title {
font-size: 1.8rem;
fill: #4F4F4F;
font-weight: 300;
}
.subtitle {
font-size: 1.0rem;
fill: #AAAAAA;
font-weight: 300;
}
.credit {
font-size: 1.2rem;
fill: #AAAAAA;
font-weight: 400;
}
.axis path, .axis tick, .axis line {
fill: none;
stroke: none;
}
.legendTitle {
font-size: 1.3rem;
fill: #4F4F4F;
font-weight: 300;
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="trafficCongestions" class="trafficCongestions"></div>
As you're using svg to just show up the text and legend, I'd say you can absolute position the canvas on top of the SVG - by CSS.
Here are the CSS changes:
div#trafficCongestions {
position: relative;
}
canvas {
position: absolute;
top: 170px;
left: 100px;
}
You can do the above using d3 style as well `cause the margins are defined in the script. I just wanted to show that this is an option to use.
var units = [];
for(var unit_i = 0; unit_i<=101;){
if(unit_i==0){
units.push(1);
unit_i = unit_i + 5;
}
else{
units.push(unit_i);
unit_i = unit_i + 4;
}
}
var times = [];
for(var times_i = 0; times_i<=1440;){
if(times_i==0){
times.push(1);
times_i = times_i + 10;
}
else{
times.push(times_i);
times_i = times_i + 9;
}
}
var newSample = [{unit:null, timestamp: null, level: null}];
//by using below method we can observe the delay is not due to the data during insertion
for(var unit=1; unit<=99; unit++){
for(var timestamp = 1; timestamp<=100; timestamp++){
var i = Math.random() * 1400;
newSample.push({unit:unit, timestamp: timestamp, level:i});
}
}
var hours = 0;
var hoursIndicator = 0;
var margin = {
top: 170,
right: 100,
bottom: 70,
left: 100
};
var width = 2500,//optimized width
//gridSize = Math.floor(width / times.length),//optimized gridsize
gridSize = 10;//if 20 each interval will have 5
height = 50 * (units.length); //optimized, the greater the length, the greater the height
//console.log("this is gridSize:" + gridSize +", this is height: " + height + ", and this is width: " + width);
//SVG container
var svg = d3.select('.trafficCongestions')
.append("svg")
//.style("position", "absolute")
.attr("width", width + margin.left + margin.right)//optimization
.attr("height", height + margin.top + margin.bottom)//optimization
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var canvas = d3.select('.trafficCongestions').append("canvas")
.attr("id", "canvas")
.attr("width", width + margin.left + margin.right)//optimization
.attr("height", height + margin.top + margin.bottom);//optimization
var context = canvas.node().getContext("2d");
context.clearRect(0, 0, width, height);
var detachedContainer = document.createElement("custom");
var dataContainer = d3.select(detachedContainer);
//Reset the overall font size
var newFontSize = width * 62.5 / 900;
//heatmap drawing starts from here
var colorScale = d3.scaleLinear()
.domain([0, d3.max(newSample, function(d, i) {return d.level; })/2, d3.max(newSample, function(d, i) {return d.level; })])
.range(["#009933", "#FFCC00", "#990000"])//obtain the max data value of count
//y-axis (solely based on data of days)
var dayLabels = svg.selectAll(".dayLabel")
.data(units)
.enter().append("text")
.text(function (d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) {
return (i) * (gridSize * 4)/*adjusts the interval distance with (n - 1) concept*/; })
.style("text-anchor", "end")
.attr("transform", "translate(-6," + gridSize + ")");
//x-axis (solely based on data of times)
var timeLabels = svg.selectAll(".timeLabel")
.data(times)
.enter().append("text")
.text(function(d, i) {
var hrs = Math.floor(d/60);
var mins = d%60;
if(hrs<10){
if(mins<10){
return "0"+hrs + ":0" + mins;
}
return "0"+ hrs + ":" + mins;
}
return hrs +":"+ mins;
})
.attr("x", function(d, i) { return i * (gridSize * 9)/*adjusts the interval distance with (n - 1) concept*/; })
.attr("y", 0)
.style("text-anchor", "middle")
.attr("transform", "translate(" + 1 + ", -6)")
var heatMap = dataContainer.selectAll("custom.rect")
.data(newSample)
.enter().append("custom")
.attr("x", function(d) {
return (d.timestamp - 1) * (gridSize);
})
.attr("y", function(d) {
//console.log(d.unit);
return (d.unit - 1) * (gridSize);
})
.classed("rect", true)
.attr("class", " rect bordered")
.attr("width", gridSize)
.attr("height", gridSize)
.attr("strokeStyle", "rgba(255,255,255, 0.6)")//to have the middle line or not
.attr("fillStyle", function(d,i){
return colorScale(d.level);
});
drawCanvas();
//Append title to the top
svg.append("text")
.attr("class", "title")
.attr("x", width/2)
.attr("y", -90)
.style("text-anchor", "middle")
.text("Sample Result");
svg.append("text")
.attr("class", "subtitle")
.attr("x", width/2)
.attr("y", -60)
.style("text-anchor", "middle")
.text("HEATMAP");
//Append credit at bottom
svg.append("text")
.attr("class", "credit")
.attr("x", width/2)
.attr("y", gridSize * (units.length+1) + 80)
.style("text-anchor", "middle");
//Extra scale since the color scale is interpolated
var countScale = d3.scaleLinear()
.domain([0, d3.max(newSample, function(d) {return d.level; })])
.range([0, width])
//Calculate the variables for the temp gradient
var numStops = 10;
countRange = countScale.domain();
countRange[2] = countRange[1] - countRange[0];
countPoint = [];
for(var i = 0; i < numStops; i++) {
countPoint.push(i * countRange[2]/(numStops-1) + countRange[0]);
}//for i
//Create the gradient
svg.append("defs")
.append("linearGradient")
.attr("id", "legendLevel")
.attr("x1", "0%").attr("y1", "0%")
.attr("x2", "100%").attr("y2", "0%")
.selectAll("stop")
.data(d3.range(numStops))
.enter().append("stop")
.attr("offset", function(d,i) {
return countScale( countPoint[i] )/width;
})
.attr("stop-color", function(d,i) {
return colorScale( countPoint[i] );
});
var legendWidth = Math.min(width, 400);//the width of the legend
//console.log(width);
//Color Legend container
var legendsvg = svg.append("g")
.attr("class", "legendWrapper")
.attr("transform", "translate(" + (width/2) + "," + (gridSize * 100 + 40) + ")");
//Draw the Rectangle
legendsvg.append("rect")
.attr("class", "legendRect")
.attr("x", -legendWidth/2)
.attr("y", 0)
.attr("width", legendWidth)
.attr("height", 10)
.style("fill", "url(#legendLevel)");
//Append title
legendsvg.append("text")
.attr("class", "legendTitle")
.attr("x", 0)
.attr("y", -10)
.style("text-anchor", "middle")
.text("Level");
//Set scale for x-axis
var xScale = d3.scaleLinear()
.range([-legendWidth/2, legendWidth/2])
.domain([ 0, d3.max(newSample, function(d) { return d.level; })] );
//Define x-axis
var xAxis = d3.axisBottom()
.ticks(5)
.scale(xScale);
//Set up X axis
legendsvg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (10) + ")")
.call(xAxis);
function drawCanvas(){
var elements = dataContainer.selectAll("custom.rect");
elements.each(function(d){
var node = d3.select(this);
context.beginPath();
context.fillStyle = node.attr("fillStyle");
context.rect(node.attr("x"), node.attr("y"), node.attr("width"), node.attr("height"));
context.fill();
context.closePath();
});
}
html { font-size: 100%; }
div#trafficCongestions {
position: relative;
}
canvas {
position: absolute;
top: 170px;
left: 100px;
}
.timeLabel, .dayLabel {
font-size: 1rem;
fill: #AAAAAA;
font-weight: 300;
}
.title {
font-size: 1.8rem;
fill: #4F4F4F;
font-weight: 300;
}
.subtitle {
font-size: 1.0rem;
fill: #AAAAAA;
font-weight: 300;
}
.credit {
font-size: 1.2rem;
fill: #AAAAAA;
font-weight: 400;
}
.axis path, .axis tick, .axis line {
fill: none;
stroke: none;
}
.legendTitle {
font-size: 1.3rem;
fill: #4F4F4F;
font-weight: 300;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<div id="trafficCongestions" class="trafficCongestions"></div>
Let me know if this makes sense. If not, let's look for other approaches.
Edit as per comments: (visual studio didn't support the CSS styling added by above approach)
Added the style using d3:
canvas.style('position', 'absolute').style('top', margin.top+'px').style('left', margin.left+'px')
And this worked.

D3.v3 Brush Strange Behavior

I'm trying to draw a brush on my histogram. The brush controls only appear after a click event (not on the initial page load). Obviously, not the desired behavior.
How do I instantiate the chart AND the brushes on the initial page load before the first click event?
// TEST Data //
var caldata = [
{"cal_start_yr": "1945"}, {"cal_start_yr": "1948"},
{"cal_start_yr": "1945"}, {"cal_start_yr": "1950"},
{"cal_start_yr": "1945"}, {"cal_start_yr": "1941"},
{"cal_start_yr": "1944"}, {"cal_start_yr": "1949"}
];
// CROSSFILTER Aggregations //
var cals = crossfilter(caldata);
var total = cals.groupAll().reduceCount().value();
var year = cals.dimension(function(d) {
return d.cal_start_yr;
});
var countYear = year.group().reduceCount();
var yearCount = countYear.all();
// Some helper AGGREGATION Values
var keys = countYear.all().map(function(d) {return d.value;}),
min = d3.min(countYear.all(), function(d) {return d.key;}),
max = d3.max(countYear.all(), function(d) {return d.key;}),
range = max - min;
// Histogram dimensions
var margin = {top: 10, right: 20, bottom: 10,left: 10 },
height = 250 - margin.top - margin.bottom,
width = 450 - margin.left - margin.right,
barPadding = 5;
// Histogram SCALES
var xScale = d3.scale.linear()
.domain([min, max])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, d3.max(countYear.all(), function(d) {return d.value;})])
.range([height / 2, 0]);
// D3 Tool Tip
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(function(d) {return d.key});
// CANVAS setup //
var histogram1 = d3.select("#histogram1").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g");
// Initiate Tooltip //
histogram1.call(tip);
// DRAW Histogram //
histogram1.selectAll("rect")
.data(yearCount)
.enter().append("rect")
.attr("x", function(d) {
return xScale(d.key) + 0.5 * (width / range)
})
.attr("width", width / range)
.attr("y", function(d) {
return yScale(d.value);
})
.attr("height", function(d) {
return (height / 2 - yScale(d.value));
})
.attr("fill", "green")
.attr("fill-opacity", .25)
.attr("stroke", "white")
.on("mouseover", tip.show)
.on("mouseout", tip.hide);
// X AXIS //
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(5)
.orient("bottom")
.tickFormat(d3.format("d"));
histogram1.append("g")
.attr("class", "axis")
.call(xAxis)
.attr("transform", "translate(" + margin.left + "," + height / 2 + ")");
var brush = d3.svg.brush()
.x(xScale)
.extent([xScale(+1945), xScale(+1946)])
.on("brush", function(d) {console.log(d);});
var brushg = histogram1.append("g")
.attr("class", "brush")
.call(brush)
brushg.selectAll("rect")
.attr("height", height / 2);
brushg.selectAll(".resize")
.append("path")
.attr("d", resizePath);
function resizePath(d) {
// Style the brush resize handles. No idea what these vals do...
var e = +(d == "e"),
x = e ? 1 : -1,
y = height / 4; // Relative positon if handles
return "M" + (.5 * x) + "," + y + "A6,6 0 0 " + e + " " + (6.5 * x) + "," + (y + 6) + "V" + (2 * y - 6) + "A6,6 0 0 " + e + " " + (.5 * x) + "," + (2 * y) + "Z" + "M" + (2.5 * x) + "," + (y + 8) + "V" + (2 * y - 8) + "M" + (4.5 * x) + "," + (y + 8) + "V" + (2 * y - 8);
}
/*** d3-tip styles */
.as-console-wrapper { max-height: 20% !important;}
.d3-tip {
line-height: 1.5;
padding: 8px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 0px;
text-align: center;
}
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
.d3-tip.n:after {
top: 100%;
left: 0;
margin: -1px 0 0;
}
/*** D3 brush */
.brush .extent {
stroke: #222;
fill-opacity: .125;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
<div id="histogram1"></div>
The brush's extent is set to a value from the scale's domain, not its range! From the docs:
The scale is typically defined as a quantitative scale, in which case the extent is in data space from the scale's domain
To set the initial extent you have to use
.extent([1945, 1946])
instead of
.extent([xScale(+1945), xScale(+1946)])
For a working demo have a look at the updated snippet:
// TEST Data //
var caldata = [
{"cal_start_yr": "1945"}, {"cal_start_yr": "1948"},
{"cal_start_yr": "1945"}, {"cal_start_yr": "1950"},
{"cal_start_yr": "1945"}, {"cal_start_yr": "1941"},
{"cal_start_yr": "1944"}, {"cal_start_yr": "1949"}
];
// CROSSFILTER Aggregations //
var cals = crossfilter(caldata);
var total = cals.groupAll().reduceCount().value();
var year = cals.dimension(function(d) {
return d.cal_start_yr;
});
var countYear = year.group().reduceCount();
var yearCount = countYear.all();
// Some helper AGGREGATION Values
var keys = countYear.all().map(function(d) {return d.value;}),
min = d3.min(countYear.all(), function(d) {return d.key;}),
max = d3.max(countYear.all(), function(d) {return d.key;}),
range = max - min;
// Histogram dimensions
var margin = {top: 10, right: 20, bottom: 10,left: 10 },
height = 250 - margin.top - margin.bottom,
width = 450 - margin.left - margin.right,
barPadding = 5;
// Histogram SCALES
var xScale = d3.scale.linear()
.domain([min, max])
.range([0, width]);
var yScale = d3.scale.linear()
.domain([0, d3.max(countYear.all(), function(d) {return d.value;})])
.range([height / 2, 0]);
// D3 Tool Tip
var tip = d3.tip()
.attr('class', 'd3-tip')
.html(function(d) {return d.key});
// CANVAS setup //
var histogram1 = d3.select("#histogram1").append("svg:svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g");
// Initiate Tooltip //
histogram1.call(tip);
// DRAW Histogram //
histogram1.selectAll("rect")
.data(yearCount)
.enter().append("rect")
.attr("x", function(d) {
return xScale(d.key) + 0.5 * (width / range)
})
.attr("width", width / range)
.attr("y", function(d) {
return yScale(d.value);
})
.attr("height", function(d) {
return (height / 2 - yScale(d.value));
})
.attr("fill", "green")
.attr("fill-opacity", .25)
.attr("stroke", "white")
.on("mouseover", tip.show)
.on("mouseout", tip.hide);
// X AXIS //
var xAxis = d3.svg.axis()
.scale(xScale)
.ticks(5)
.orient("bottom")
.tickFormat(d3.format("d"));
histogram1.append("g")
.attr("class", "axis")
.call(xAxis)
.attr("transform", "translate(" + margin.left + "," + height / 2 + ")");
var brush = d3.svg.brush()
.x(xScale)
.extent([1945, 1946])
.on("brush", function(d) {console.log(brush.extent());});
var brushg = histogram1.append("g")
.attr("class", "brush")
.call(brush)
brushg.selectAll("rect")
.attr("height", height / 2);
brushg.selectAll(".resize")
.append("path")
.attr("d", resizePath);
function resizePath(d) {
// Style the brush resize handles. No idea what these vals do...
var e = +(d == "e"),
x = e ? 1 : -1,
y = height / 4; // Relative positon if handles
return "M" + (.5 * x) + "," + y + "A6,6 0 0 " + e + " " + (6.5 * x) + "," + (y + 6) + "V" + (2 * y - 6) + "A6,6 0 0 " + e + " " + (.5 * x) + "," + (2 * y) + "Z" + "M" + (2.5 * x) + "," + (y + 8) + "V" + (2 * y - 8) + "M" + (4.5 * x) + "," + (y + 8) + "V" + (2 * y - 8);
}
/*** d3-tip styles */
.d3-tip {
line-height: 1.5;
padding: 8px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
border-radius: 0px;
text-align: center;
}
.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "\25BC";
position: absolute;
text-align: center;
}
.d3-tip.n:after {
top: 100%;
left: 0;
margin: -1px 0 0;
}
/*** D3 brush */
.brush .extent {
stroke: #222;
fill-opacity: .125;
shape-rendering: crispEdges;
}
.as-console-wrapper { max-height: 30% !important;}
<script src="https://d3js.org/d3.v3.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3-tip/0.7.1/d3-tip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter/1.3.12/crossfilter.min.js"></script>
<div id="histogram1"></div>

In D3 bar graph, y-axis ordinal scale is not aligning properly with bars

I was following Mike's tutorial Let's make a bar graph part II, part III for the bar graph in d3.
I end up with a horizontal bar graph.
The Problem is I'm not able to set the y-axis labels aligned with its respective bar, maybe I'm somewhere wrong with ordinal scale or setting up the y position of the bars.
Also, the graph bars are starting from the top instead of baseline.
var options = {
margin: {
top: 0,
right: 30,
bottom: 0,
left: 50
},
width: 560,
height: 400,
element: 'body',
colors: ["#f44336", "#e91e63", "#673ab7", "#3f51b5", "#2196f3", "#03a9f4", "#00bcd4", "#009688", "#4caf50", "#8bc34a", "#cddc39", "#ffeb3b", "#ffc107", "#ff9800", "#ff5722", "#795548", "#607d8b"]
};
options.mWidth = options.width - options.margin.left - options.margin.right;
options.mHeight = options.height - options.margin.top - options.margin.bottom;
var _colorScale = d3.scale.ordinal()
// .domain([minValue,maxValue])
.range(options.colors);
var items = Math.round((Math.random() * 10) + 3);
var data = [];
for (var i = 0; i < items; i++) {
data.push({
label: 'label' + i,
value: Math.random() * 100
});
}
var _barThickness = 20;
var width = options.mWidth,
height = options.mHeight;
var svg = d3.select(options.element)
.append("svg")
.attr("width", width).attr("height", height)
.attr("viewBox", "0 0 " + options.width + " " + options.height)
//.attr("preserveAspectRatio", "xMinYMin meet")
.append("g");
svg.attr("transform", "translate(" + options.margin.left * 2 + "," + options.margin.top + ")");
var maxValue = 0,
minValue = 0;
for (var i = 0; i < data.length; i++) {
maxValue = Math.max(maxValue, data[i].value);
minValue = Math.min(minValue, data[i].value);
}
var scales = {
x: d3.scale.linear().domain([0, maxValue]).range([0, width / 2]),
y: d3.scale.ordinal().rangeRoundBands([0, height], .1)
}
scales.y.domain(data.map(function(d) {
return d.label;
}));
var bars = svg.append("g")
.attr("class", "bar");
var xAxis = d3.svg.axis()
.scale(scales.x)
.orient("bottom")
.ticks(5);
var yAxis = d3.svg.axis()
.scale(scales.y)
.orient("left");
var xaxis = svg.append("g")
.attr("class", "x axis")
.attr('transform', 'translate(' + 0 + ',' + height + ')')
.call(xAxis)
.append("text")
.attr("x", width / 2)
.attr("dy", "3em")
.style("text-anchor", "middle")
.text("Durations in hours");
var yaxis = svg.append("g")
.attr("class", "y axis")
.attr('transform', 'translate(' + 0 + ',' + 0 + ')')
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -options.margin.left)
.attr("x", -height / 2)
.attr("dy", ".71em")
.style("text-anchor", "middle")
.text("Labels");
var bar = bars.selectAll('rect.bar').data(data);
var rect = bar.enter()
.append('g')
.attr('transform', function(d, i) {
return 'translate(0,' + parseInt(i * _barThickness + 2) + ')';
});
rect.append('rect')
.attr('class', 'bar')
.attr('fill', function(d) {
return _colorScale(d.value);
})
.attr('width', function(d) {
return scales.x(d.value);
})
.attr('height', _barThickness - 1)
.attr('y', function(d, i) {
return (i * _barThickness);
})
rect.append('text')
.attr('x', function(d) {
return scales.x(d.value) + 2;
})
.attr('y', function(d, i) {
return (i * _barThickness);
})
.attr('dy', '0.35em')
.text(function(d) {
return Math.round(d.value);
});
svg {
width: 100%;
height: 100%;
}
text {
font-size: 0.8em;
line-height: 1em;
}
path.slice {
stroke-width: 2px;
}
polyline {
opacity: .3;
stroke: black;
stroke-width: 2px;
fill: none;
}
.axis {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
Problem 1:
Instead of this:
var _barThickness = 20;
Do this:
var _barThickness = scales.y.rangeBand();
Read here
If you want to regulate the thickness
Instead of this:
y: d3.scale.ordinal().rangeRoundBands([0, height], .1)
Do this:
y: d3.scale.ordinal().rangeRoundBands([0, height], .7)
Problem 2:
Incorrect transform.
Instead of this:
var rect = bar.enter()
.append('g')
.attr('transform', function(d, i) {
return 'translate(0,' + parseInt(i * _barThickness + 2) + ')';
});
Do this:
var rect = bar.enter()
.append('g');
Problem 3:
Incorrect calculation of y for the bars.
.attr('y', function(d, i) {
return (i * _barThickness);
})
Do this:
.attr('y', function(d, i) {
return scales.y(d.label);
})
working code here

Legend to be aligned after pie chart but getting aligned before

Hello I want to right align my legend after the pie chart. But with my codes they are getting aligned to left before pie chart. What CSS changes should I make to do this.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>Testing Pie Chart</title>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<style type="text/css">
/* #container {
margin: 5%;
height: 50%;
width: 50%;
}*/
#chart {
position: absolute;
background-color: #eee;
/* height: 50%;
width: 50%; */
}
#chart legend{
position: absolute;
}
.tooltip {
background: #eee;
box-shadow: 0 0 5px #999999;
color: #900C3F;
display: inline-block;
font-size: 12px;
position: absolute;
text-align: center;
width: 10%;
z-index: 10;
opacity: 1;
}
rect {
stroke-width: 2;
}
path {
stroke: #ffffff;
stroke-width: 0.5;
}
div.tooltip {
position: absolute;
z-index: 999;
padding: 10px;
background: #f4f4f4;
border: 0px;
border-radius: 3px;
pointer-events: none;
font-size: 11px;
color: #080808;
line-height: 16px;
border: 1px solid #d4d4d4;
}
</style>
</head>
<body>
<div id="container">
<svg id="chart" viewBox="0 0 960 500" perserveAspectRatio="xMinYMid">
<div id="toolTip" class="tooltip" style="opacity: 0;"></div>
<script type="text/javascript">
var div = d3.select("#toolTip");
var data = [
["192.168.12.1", 20],
["76.09.45.34", 40],
["34.91.23.76", 80],
["192.168.19.32", 16],
["192.168.10.89", 50],
["192.178.34.07", 18],
["192.168.12.98", 30]];
var data = data.map(function(d) {
return {
IP: d[0],
count: d[1]
};
});
var width = 500,
height = 300;
var radius = Math.min(width, height) / 2 - 50;
var legendRectSize = 18,
legendSpacing = 4;
var color = d3.scale.category20b();
var arc = d3.svg.arc()
.outerRadius(radius);
var arcOver = d3.svg.arc()
.outerRadius(radius + 5);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.count; });
var labelArc = d3.svg.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
var svg = d3.select("#chart").append("svg")
.datum(data)
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width/2 + "," + height/2 + ")");
var arcs = svg.selectAll(".arc")
.data(pie)
.enter().append("g")
.attr("class", "arc");
var arcs2 = svg.selectAll(".arc2")
.data(pie)
.enter().append("g")
.attr("class", "arc2");
arcs.append("path")
.attr("fill", function(d, i) { return color(i); })
.on("mouseover", function(d) {
var htmlMsg="";
div.transition()
.style("opacity",0.9);
var total = d3.sum(data.map(function(d) {
return d.count;
}));
var percent = Math.round(1000 * d.data.count / total) / 10;
div.html(
"IP :"+ d.data.IP +""+"<br/>"+
"Count : " + d.data.count +"<br/>" +
"Percent: " + percent + '%'+ htmlMsg)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY) + "px");
svg.selectAll("path").sort(function (a, b) {
if (a != d) return -1;
else return 1;
});
var endAngle = d.endAngle + 0.1;
var startAngle = d.startAngle - 0.1;
var arcOver = d3.svg.arc()
.outerRadius(radius + 10).endAngle(endAngle).startAngle(startAngle);
d3.select(this)
.attr("stroke","white")
.transition()
.ease("bounce")
.duration(1000)
.attr("d", arcOver)
.attr("stroke-width",6);
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
d3.select(this).transition()
.attr("d", arc)
.attr("stroke","none");
})
.transition()
.ease("bounce")
.duration(2000)
.attrTween("d", tweenPie);
function tweenPie(b) {
b.innerRadius = 0;
var i = d3.interpolate({startAngle: 0, endAngle: 0}, b);
return function(t) { return arc(i(t)); };
}
var k=0;
arcs2.append("text")
.transition()
.ease("elastic")
.duration(2000)
.delay(function (d, i) {
return i * 250;
})
.attr("x","6")
.attr("dy", ".35em")
.text(function(d) { if(d.data.count >0){ k = k+1; return d.data.count;} }) //We can define any value for (d.data.count >__ according to our need. Like if we have smaller values less than 10 then no need to dislay them as they can be overlapped on pie slice margins)// If not needed to display make this comment
.attr("transform", function(d) { if (k >1){return "translate(" + labelArc.centroid(d) + ") rotate(" + angle(d) + ")";} else{return "rotate(-360)";} })
.attr("font-size", "10px");
function type(d) {
d.count = +d.count;
return d;
}
function angle(d) {
var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
return a > 90 ? a - 180 : a;
}
var legend = d3.select("#chart")
.append("svg")
.attr("class", "legend")
.attr("width", radius+50)
.attr("height", radius * 2)
.selectAll("g")
.data(color.domain())
.enter()
.append("g")
.attr("transform", "translate(" + width * 1/4 + "," + height * 1/4 + ")")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append('rect')
.attr('width', legendRectSize)
.attr('height', legendRectSize)
.style('fill', color)
.style('stroke', color);
legend.append('text')
.attr('x', legendRectSize + legendSpacing)
.attr('y', legendRectSize - legendSpacing)
.data(data)
.text(function(d,i) { return d.IP; });
</script>
</svg>
</div>
<script type="text/javascript">
var chart = $("#chart"),
aspect = chart.width() / chart.height(),
container = chart.parent();
$(window).on("resize", function() {
var targetWidth = container.width();
var targetHeight = container.height();
chart.attr("width", targetWidth);
chart.attr("height", Math.round(targetWidth / aspect));
}).trigger("resize");
</script>
</script>
</body>
</html>
Please give some idea how to solve this problem. I am stuck in this code.
Thanks for help in advance.
You need to add x and y attributes to the legend.
legend.attr("x", width - 65)
.attr("y", 25)
Here is the full code and working example for you

Categories