So, I recently decided to explore the D3 library, and of course, I was using freecodecamp. D3 sounds like an awesome front end library which enables you do things from manipulating your DOM elements to creating visualizations using SVG and Canvas. From what I've seen so far it's an awesome library.
To use it, all you need is to reference the script from a CDN or include it in your project. Just one script, no configurations. Well, for now...
An Example Then
Ok, the most basic thing you can do with this library is to manipulate DOM elements
<body>
<script>
d3.select("body")
.append("h1")
.text("Hello D3");
</script>
</body>
Here, we used D3's select()
method to select the body element. Then add a h1 node and and the text "Hello D3" to that node.
A more involved example would be
<body>
<script>
const dataset = [12, 31,22,17, 25, 18, 29, 14, 9];
d3.select("body")
.selectAll("h2")
.data(dataset)
.enter()
.append("h2")
.text("New Title")
</script>
</body>
Here, the library selects the body
tag and selects all h2
elements in it. It then gets data from the array called dataset
. The enter method then enters each array item into the DOM tree, where new tags are added with
innerText
called "New Title". Here, d3 actually selects elements that don't exist yet and appends text to them based on data
How Cool Can it get?
Very cool infact. You can use JS functions, conditions, callbacks to apply styles to elements. In this simple example, we would add style conditionally based on magnitude of values.
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("h2") //h2 elements which don't exist yet
.data(dataset)
.enter()
.append("h2") //now they do
.text((d) => (d + " USD"))
.style("color", d => d < 20 ? "red" : "green")
</script>
</body>
A simple bar chart.
Let's create a simple bar chart using data in an array and CSS styling
<style>
.bar {
width: 25px;
height: 100px;
margin: 2px;
display: inline-block;
background-color: cornflowerblue;
}
</style>
<body>
<script>
const dataset = [12, 31, 22, 17, 25, 18, 29, 14, 9];
d3.select("body").selectAll("div")
.data(dataset)
.enter()
.append("div")
.attr("class", "bar")
.style("height", d => d * 10 + "px")
</script>
</body>
Here, the following are happening:
- The
.attr()
sets the HTML attribute for the selected div elements, in this case, the attribute is theclass
attribute. - The style is attached based on the class defined in the CSS block.
- The callback in the style method sets the height and increases it by 10. The unit used here is the pixel.
So there you have it. A very simple example that sets you up and running using this awesome data visualization library. I'd be making more posts in the future using D3.
Top comments (0)