Just mucking about with D3. Trying to remember how it works.
Last active
February 21, 2019 18:54
-
-
Save fogonwater/6bd6401a39d4aefadcb1 to your computer and use it in GitHub Desktop.
D3 bar chart tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="eng"> | |
<head> | |
<meta charset="UTF-8"> | |
<style> | |
body {text-align:center} | |
svg { font-family: Courier;} | |
</style> | |
<title>Labelled Bar Chart</title> | |
<script src="https://d3js.org/d3.v5.js"></script> | |
</head> | |
<body> | |
<svg width=600 height=500> | |
<text class="title" x=0 y=30>This example is overly complicated. Simplify with scales.</text> | |
</svg> | |
<script type="text/javascript"> | |
console.clear() | |
var data = [], | |
num_elements = 20, | |
max_value = 30 | |
// Generate some data | |
for (var i = 0; i < num_elements; i++) { | |
var newNum = Math.ceil( Math.random() * max_value ); | |
data.push(newNum); | |
} | |
const svg = d3.select("svg"), | |
width = +svg.attr("width"), | |
height = +svg.attr("height"), | |
margin= 20 | |
barPadding = 1, | |
barSpan = width / data.length | |
y = d3.scaleLinear() | |
.range([height-margin, margin]) | |
.domain([0, max_value]) | |
svg.selectAll("rect") | |
.data(data) | |
.enter() | |
.append("rect") | |
.attr("x", (d, i) => i * barSpan) | |
.attr("y", d => height - y(d)) | |
//.attr("y", d => height - (d * 4)) | |
.attr("width", barSpan - barPadding) | |
.attr("height", d => y(d)) | |
.attr("fill", d => d == Math.max.apply(Math, data) ? "crimson" : '#B0A6A4'); | |
svg.selectAll("text") | |
.data(data) | |
.enter() | |
.append("text") | |
.text(d => d > 4 ? d : '') | |
.attr("x", (d, i) => | |
i * (width / data.length) + (width / data.length - barPadding) / 2 | |
) | |
.attr("y", d => height - (d * 4) + 14) | |
.attr("font-family", "sans-serif") | |
.attr("font-size", "11px") | |
.attr("fill", "white") | |
.attr("text-anchor", "middle"); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment