Skip to content

Instantly share code, notes, and snippets.

@eychang9
Last active January 21, 2018 20:19
Show Gist options
  • Save eychang9/0f367f48a725a30d69615b7d0beddaa5 to your computer and use it in GitHub Desktop.
Save eychang9/0f367f48a725a30d69615b7d0beddaa5 to your computer and use it in GitHub Desktop.
Ch10_Bar_Tooltips
license: mit

Built with blockbuilder.org

Base code for Chapter 9 bar chart exercises. This will use tool tips from Chapter 10 in order to provide additional data.

forked from eychang9's block: Ch9_Bar_Base

<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
.txtLabel {
font-family: Century Gothic;
font-size: 12px;
}
</style>
</head>
<body>
<script>
// Dataset and other constants
var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];
var svgW = 900;
var svgH = 500;
var pad = 100;
// Develop axial scales
var xScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.rangeRound([pad, svgW-pad])
.paddingInner(0.05);
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset, function (d) { return (d);})])
.rangeRound([svgH-pad, pad])
// Establish SVG
var svg = d3.select("body")
.append("svg")
.attr("width", svgW)
.attr("height", svgH)
// Draw label box
svg.append("rect")
.attr("x", (svgW/2)-200)
.attr("y", (svgH-pad+20))
.attr("width", 400)
.attr("height", pad-40)
.attr("rx", 15)
.attr("ry", 15);
svg.append("rect")
.attr("x", (svgW/2)-190)
.attr("y", (svgH-pad+25))
.attr("width", 380)
.attr("height", pad-50)
.attr("rx", 15)
.attr("ry", 15)
.attr("fill", "white");
// Draw bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function (d,i) { return xScale(i); })
.attr("y", function (d) { return yScale(d); })
.attr("width", xScale.bandwidth())
.attr("height", function (d) { return (svgH-pad-yScale(d)); })
.attr("fill", function (d) { return "rgb(0,0," + d*10 + ")" })
.on("mouseover", function (d) {
d3.select(this)
.attr("fill", "yellow");
svg.append("text")
.attr("id", "tooltip")
.attr("x", svgW/2)
.attr("y", svgH-(pad/2))
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("font-weight", "bold")
.attr("fill", "black")
.text("This value is " + d);
})
.on("mouseout", function (d) {
d3.select("#tooltip").remove();
d3.select(this)
.attr("fill", function (d) { return "rgb(0,0," + d*10 + ")" })
});
// Draw text
/*svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.attr("x", function (d,i) { return (xScale(i) + 0.5 * xScale.bandwidth());})
.attr("y", function (d) { return (yScale(d) + 15); })
.text(function (d) { return (d);})
.attr("fill", "rgb(255,255,255)")
.attr("text-anchor", "middle")
.attr("class", "txtLabel"); */
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment