Skip to content

Instantly share code, notes, and snippets.

@davelandry
Last active August 22, 2016 15:24
Show Gist options
  • Save davelandry/7760febcda3375b39e1f to your computer and use it in GitHub Desktop.
Save davelandry/7760febcda3375b39e1f to your computer and use it in GitHub Desktop.
Custom Text and Number Formatting

By default D3plus tries to print numbers and text in a clean, consistent way. Sometimes, customization may be required that is outside of this basic formatting.

The .format( ) method provides access to override the default "text" and "number" formatting functions. Each function gets passed both the value being formatted, and the key (if applicable) associated with that value.

In this example, the label "usd" is being changed to "Trade Value" and all values are being prefixed with "$" and suffixed with "USD". Hover over one of the Tree Map squares to see the modified output.

Featured on D3plus.org

<!doctype html>
<meta charset="utf-8">
<script src="//d3plus.org/js/d3.js"></script>
<script src="//d3plus.org/js/d3plus.js"></script>
<div id="exports"></div>
<script>
// sample data array
var trade_data = [
{"usd": 34590873460, "product": "Oil"},
{"usd": 12897429187, "product": "Cars"},
{"usd": 8974520985, "product": "Airplanes"},
{"usd": 9872342, "product": "Apples"},
{"usd": 6897234098, "product": "Shoes"},
{"usd": 590834587, "product": "Glass"},
{"usd": 987234261, "product": "Horses"}
]
// instantiate d3plus
var visualization = d3plus.viz()
.container("#exports")
.data(trade_data)
.type("tree_map")
.id("product")
.size("usd")
.format({
"text": function(text, params) {
if (text === "usd") {
return "Trade Value";
}
else {
return d3plus.string.title(text, params);
}
},
"number": function(number, params) {
var formatted = d3plus.number.format(number, params);
if (params.key === "usd") {
return "$" + formatted + " USD";
}
else {
return formatted;
}
}
})
.draw()
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment