Built with blockbuilder.org
Last active
June 10, 2019 08:15
-
-
Save GitNoise/dda48361f24f36e779c8cfab4be78bf4 to your computer and use it in GitHub Desktop.
Overlapping labels - d3fc-label-layout
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> | |
<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; } | |
svg { border: 1px solid red; } | |
rect { | |
fill: none; | |
stroke: red; | |
} | |
</style> | |
<script src="https://unpkg.com/d3@5.5.0"></script> | |
<script src="https://unpkg.com/d3fc@14.0.1"></script> | |
<script src="https://cdn.jsdelivr.net/npm/d3fc-label-layout@5.1.0/build/d3fc-label-layout.js"></script> | |
</head> | |
<body> | |
<script> | |
// Feel free to change or delete any of the code you see in this editor! | |
var svg = d3.select("body").append("svg") | |
.attr("width", 400) | |
.attr("height", 400); | |
const xyScale = d3.scaleLinear() | |
.domain([0, 100]) | |
.range([0, 400]); | |
const labelPadding = 5; | |
// the component used to render each label | |
const textLabel = fc.layoutTextLabel() | |
.padding(labelPadding) | |
.value(d => d.emperor); | |
// a strategy that combines simulated annealing with removal | |
// of overlapping labels | |
const strategy = fc.layoutGreedy().bounds({x: xyScale(50), y:0, width: 200, height: xyScale(100)}); | |
// create the layout that positions the labels | |
const labels = fc.layoutLabel(strategy) | |
.size((d, i, g) => { | |
// measure the label and add the required padding | |
const textSize = g[i].getElementsByTagName('text')[0].getBBox(); | |
return [textSize.width + labelPadding * 2, textSize.height + labelPadding * 2]; | |
}) | |
.position(d => [xyScale(50), xyScale(d.value)]) | |
.component(textLabel); | |
const data = [ | |
{value: 31, emperor:'nero'}, | |
{value: 33, emperor:'augustus'}, | |
{value: 35, emperor:'trajan'}, | |
{value: 37, emperor:'claudius'}, | |
{value: 39, emperor:'tiberius'}, | |
]; | |
// render! | |
svg.datum(data) | |
.call(labels); | |
</script> | |
</body> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment