Bar position in d3 is not matching with axis - javascript

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>

Related

D3.js Adding legend to the Responsive bar chart

I have found a simple responsive bar chart from this Link. So, I have done some little modification into this and also added legends into bar chart. Chart is responsive but not the legends. I have been working on this since days. I have tried appending legends into x-axis that doesn't work also.
<!doctype html>
<html lang="en">
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<style>
.axis path,
.axis line {
fill: none;
stroke: #bdbdbd;
}
.axis text {
font-family: 'Open Sans regular', 'Open Sans';
font-size: 13px;
}
.bar {
fill: #8bc34a;
}
.bar:hover {
fill: #039be4;
}
</style>
<div id ="chartID"></div>
<script>
var data = [{
"letter": "a",
"frequency": "4.84914547592537",
"Color": "#D3D3D3"
},
{
"letter": "b",
"frequency": "4.86872684269123",
"Color": "#D3D3D3"
},
{
"letter": "c",
"frequency": "6.63842861065779",
"Color": "#000000"
},
{
"letter": "d",
"frequency": "6.53280838923937",
"Color": "#000000"
}
]
var data2 = [];
for (var i = 0; i < 2; i++) {
data2.push(data[i]);
}
var color_hash = {
0: ["Control", "#D3D3D3"],
1: ["Case", "#000000"]
}
var margin = {
top: 30,
right: 100,
bottom: 20,
left: 80
};
var width = 960 - margin.left - margin.right;
var height = 500 - margin.top - margin.bottom;
var xScale = d3.scale.ordinal().rangeRoundBands([0, width], .1)
var yScale = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left");
var svgContainer = d3.select("#chartID").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 + ")");
xScale.domain(data.map(function (d) {
return d.letter;
}));
yScale.domain([0, d3.max(data, function (d) {
return d.frequency;
})]);
var xAxis_g = svgContainer.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + (height) + ")")
.call(xAxis);
var yAxis_g = svgContainer.append("g")
.attr("class", "y axis")
.call(yAxis)
.append("text")
.attr("dx", "-10em")
.attr("transform", "rotate(-90)")
.attr("y", 6).attr("dy", "-4.0em")
.style("text-anchor", "end").text("Expression values");
svgContainer.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function (d) {
return xScale(d.letter);
})
.attr("width", xScale.rangeBand())
.attr("y", function (d) {
return yScale(d.frequency);
})
.attr("height", function (d) {
return height - yScale(d.frequency);
})
.style("fill", function (d) {
return d.Color;
});
// Add Legends
var legend = svgContainer.append("g")
// .attr("transform", "translate(0," + (10) + ")")
// .attr("x", width - 100)
// .attr("y", 250)
// .attr("height", 100)
// .attr("width", 100);
legend.selectAll('g').data(data2)
.enter()
.append('g')
.each(function (d, i) {
var g = d3.select(this);
g.append("rect")
// .attr("class", "legend")
.attr("x", width)
.attr("y", i * 25)
.attr("width", 10)
.attr("height", 10)
.style("fill", color_hash[String(i)][1]);
g.append("text")
// .attr("class", "legend")
.attr("x", width - 20 * -1)
.attr("y", i * 25 + 8)
// .attr("height", 30)
// .attr("width", 100)
// .style("text-anchor", "end")
.style("font-size", 16)
.text(color_hash[String(i)][0]);
});
d3.select(window).on('resize', resize);
function resize() {
// console.log('----resize function----');
// update width
width = parseInt(d3.select('#chartID').style('width'), 10);
width = width - margin.left - margin.right;
height = parseInt(d3.select("#chartID").style("height"));
height = height - margin.top - margin.bottom;
// console.log('----resiz width----' + width);
// console.log('----resiz height----' + height);
// resize the chart
if (width < 870) {
//xScale.range([0, width]);
xScale.rangeRoundBands([0, width], .1);
yScale.range([height, 0]);
yAxis.ticks(Math.max(height / 50, 2));
xAxis.ticks(Math.max(width / 50, 2));
d3.select(svgContainer.node().parentNode)
.style('width', (width + margin.left + margin.right) + 'px');
svgContainer.selectAll('.bar')
.attr("x", function (d) {
return xScale(d.letter);
})
.attr("width", xScale.rangeBand());
// svgContainer.selectAll('.legend')
// .attr("x", function (d) {
// return ;
// })
// .attr("width", xScale.rangeBand());
svgContainer.select('.x.axis').call(xAxis.orient('bottom'));
// svgContainer.select('.legend');
}
}
</script>
</html>
Need some help for this.
Thank you.

d3.js scaleBand()'s ticks coming out of place

I am using scaleBand() for both x and y axes for a bar chart. For some reason, the height of the bars are in between the ticks of the y axis. I would appreciate any help. Here is my code:
var margin_ = { top: 20, right: 20, bottom: 30, left: 40 },
width_ = 960 - margin_.left - margin_.right,
height_ = 500 - margin_.top - margin_.bottom;
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 + ")");
var x = d3.scaleBand()
.range([0, width_])
.padding(0.2)
var y = d3.scaleBand()
.range([height_, 0]);
x.domain(satisfactScaleKeyValues);
y.domain(graphYvalues);
svg_.selectAll(".bar")
.data(datas)
.enter().append("rect")
.attr("class", "bar__")
.attr("x", function (d) { return x(d.variable); })
.attr("width", x.bandwidth())
.attr("y", function (d) { return y(d.satisLevel); })
.attr("height", function (d) { return height_ - y(d.satisLevel); });
// add the x Axis
svg_.append("g")
.attr("transform", "translate(0," + height_ + ")")
.call(d3.axisBottom(x));
// add the y Axis
svg_.append("g")
.call(d3.axisLeft(y))
You should use d3.scalePoint, which would provide a better translation from an ordinal domain to linear points on a range:
let datas = [{variable: 1, satisLevel: "Neutral"}]
var margin_ = { top: 20, right: 50, bottom: 30, left: 75 },
width_ = 960 - margin_.left - margin_.right,
height_ = 500 - margin_.top - margin_.bottom;
var svg_ = d3.select("body").append("svg")
.attr("width", width_ + margin_.left + margin_.right)
.attr("height", height_ + margin_.top + margin_.bottom)
var g = svg_.append("g")
.attr("transform",
"translate(" + margin_.left + "," + margin_.top + ")");
var x = d3.scaleBand()
.range([0, width_])
.padding(0.2)
var y = d3.scalePoint()
.range([height_, 0])
.padding(0.2)
x.domain([1]);
y.domain(["Not satisfied", "Neutral", "Satisfied"]);
g.selectAll(".bar")
.data(datas)
.enter().append("rect")
.attr("class", "bar__")
.attr("x", function (d) { return x(d.variable); })
.attr("width", x.bandwidth())
.attr("y", function (d) { return y(d.satisLevel); })
.attr("height", function (d) { return height_ - y(d.satisLevel); });
// add the x Axis
g.append("g")
.attr("transform", "translate(0," + height_ + ")")
.call(d3.axisBottom(x));
// add the y Axis
g.append("g")
.call(d3.axisLeft(y))
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
If you want the height of the lowest Satisfaction Level to be more than zero, you can add padding to the scalePoint, like in the example.

Tooltip not working nor displaying on D3 scatter plot

I would like to add a tooltip to the line chart, where each data point displays a text box upon hover, as follows:
-----------------|
x-coordinate: ## |
y-coordinate: ## |
-----------------|
The working snippet for the working graph is posted below. But I will comment out the tooltip block to plot the chart.
Thanks.
var margin = {top: 50, right: 50, bottom: 50, left: 50}
, width = window.innerWidth - margin.left - margin.right
, height = window.innerHeight - margin.top - margin.bottom;
//labels
var labels = ['Mon','Tue','Thur','Frid'];
var yvals = [12,11,0,18];
// X scale
var xScale = d3.scalePoint()
.domain(labels) // input
.range([0, width-1]); // output
// Y scale
var yScale = d3.scaleLinear()
.domain([0, 20])
.range([height,0]);
var line = d3.line()
.x(function(d, i) { return xScale(labels[i]); })
.y(function(d) { return yScale(d.y); })
.curve(d3.curveMonotoneX)
var dataset = d3.range(yvals.length).map(function(d,i) { return {"y": yvals[i]} })
//Tooltip
//var tip = d3.select('body')
//.append('div')
//.attr('class', 'tip')
//.html('number:'+ function(d,i) return {data[data.i]})
// .style('border', '1px solid steelblue')
// .style('padding', '5px')
//.style('position', 'absolute')
// .style('display', 'none')
//.on('mouseover', function(d, i) {
// tip.transition().duration(0);
// })
// .on('mouseout', function(d, i) {
// tip.style('display', 'none');
// });
// SVGs
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("width", "100%")
.attr("height", "100%")
.attr("fill", "white");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// x axis call
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
//.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale));
// y axis call
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("path")
.datum(dataset)
.attr("class", "line")
.attr("d", line);
// 12. Appends a circle for each datapoint
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d, i) { return xScale(labels[i]) })
.attr("cy", function(d,i) { return yScale(yvals[i]) })
.attr("r", 3);
//.on('mouseover', function(d, i) {
// tip.transition().duration(0);
// })
svg.append("text")
.attr("class", "title")
.attr("x", width/2)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Testing");
.line {
fill: none;
stroke: orange;
stroke-width: 1;
}
.dot {
fill: brown;
stroke: #fff;
}
<!DOCTYPE html>
<meta charset="utf-8">
<style type="text/css">
</style>
<body>
</body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>
</script>
I have just made a few changes to the mousemove event.
var margin = {
top: 50,
right: 50,
bottom: 50,
left: 50
},
width = window.innerWidth - margin.left - margin.right,
height = window.innerHeight - margin.top - margin.bottom;
//labels
var labels = ['Mon', 'Tue', 'Thur', 'Frid'];
var yvals = [12, 11, 0, 18];
// X scale
var xScale = d3.scalePoint()
.domain(labels) // input
.range([0, width - 1]); // output
// Y scale
var yScale = d3.scaleLinear()
.domain([0, 20])
.range([height, 0]);
var line = d3.line()
.x(function(d, i) {
return xScale(labels[i]);
})
.y(function(d) {
return yScale(d.y);
})
.curve(d3.curveMonotoneX)
var dataset = d3.range(yvals.length).map(function(d, i) {
return {
"y": yvals[i]
}
})
var tip = d3.select('body').append("div")
.attr("class", "tip");
// SVGs
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("width", "100%")
.attr("height", "100%")
.attr("fill", "white");
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// x axis call
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
//.call(d3.axisBottom(xScale));
.call(d3.axisBottom(xScale));
// y axis call
svg.append("g")
.attr("class", "y axis")
.call(d3.axisLeft(yScale));
svg.append("path")
.datum(dataset)
.attr("class", "line")
.attr("d", line);
// 12. Appends a circle for each datapoint
svg.selectAll(".dot")
.data(dataset)
.enter().append("circle") // Uses the enter().append() method
.attr("class", "dot") // Assign a class for styling
.attr("cx", function(d, i) {
return xScale(labels[i])
})
.attr("cy", function(d, i) {
return yScale(yvals[i])
})
.attr("r", 3)
.on("mouseover", function() {
tip.style("display", null);
})
.on("mouseout", function() {
tip.style("display", "none");
})
.on("mousemove", function(d) {
return tip
.style("left", d3.event.pageX + "px")
.style("top", d3.event.pageY + 10 + "px")
.style("visibility", "visible")
.html(function() {
return '<div style="border:1px solid #ccc;">' +
'<p style="font-weight:bold;">' + d.y + '</p>' +
'</div>';
})
})
svg.append("text")
.attr("class", "title")
.attr("x", width / 2)
.attr("y", 0 - (margin.top / 2))
.attr("text-anchor", "middle")
.text("Testing");
.line {
fill: none;
stroke: orange;
stroke-width: 1;
}
.dot {
fill: brown;
stroke: #fff;
}
.tip {
position: absolute;
border: 1px solid steelblue;
visibility: hidden;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.0.0/d3.min.js"></script>
Here is the working jsFiddle
Hope it helps :)

Unable to position tooltip on d3js bar chart

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');
})

X axis values for histogram

How should one define values range for X axis?
I've took example which used decimal values in range 0 to 1, and this clearly doesn't work for greater numbers.
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar rect {
fill: steelblue;
}
.bar text {
fill: #fff;
font: 10px sans-serif;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// var data = d3.range(1000).map(d3.randomBates(10));
var data = [1321017167, 1421017167, 1421017167, 1421017167, 1521017167, 1521017167];
var formatCount = d3.format(",.0f");
var svg = d3.select("svg"),
margin = {top: 10, right: 30, bottom: 30, left: 30},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.rangeRound([0, width]);
var bins = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(20))
(data);
var y = d3.scaleLinear()
.domain([0, d3.max(bins, function(d) { return d.length; })])
.range([height, 0]);
var bar = g.selectAll(".bar")
.data(bins)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
</script>
By default, the domain of a linear scale is [0, 1]. You just copied that code from Mike Bostock without changing the domain. In his original code the domain is, coincidentally, the default domain, but in your code you have to define it:
var x = d3.scaleLinear()
.rangeRound([0, width])
.domain(d3.extent(data))//domain here
Here I'm using d3.extent, but you can use any other array you want.
Here is your code with that change only:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar rect {
fill: steelblue;
}
.bar text {
fill: #fff;
font: 10px sans-serif;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// var data = d3.range(1000).map(d3.randomBates(10));
var data = [1321017167, 1421017167, 1421017167, 1421017167, 1521017167, 1521017167];
var formatCount = d3.format(",.0f");
var svg = d3.select("svg"),
margin = {top: 10, right: 30, bottom: 30, left: 30},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleLinear()
.rangeRound([0, width])
.domain(d3.extent(data))
var bins = d3.histogram()
.domain(x.domain())
.thresholds(x.ticks(20))
(data);
var y = d3.scaleLinear()
.domain([0, d3.max(bins, function(d) { return d.length; })])
.range([height, 0]);
var bar = g.selectAll(".bar")
.data(bins)
.enter().append("g")
.attr("class", "bar")
.attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; });
bar.append("rect")
.attr("x", 1)
.attr("width", x(bins[0].x1) - x(bins[0].x0) - 1)
.attr("height", function(d) { return height - y(d.length); });
bar.append("text")
.attr("dy", ".75em")
.attr("y", 6)
.attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2)
.attr("text-anchor", "middle")
.text(function(d) { return formatCount(d.length); });
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
</script>
PS: You'll have to adjust the horizontal position of the rectangles.

Categories