The code for this tutorial can be downloaded here https://github.com/connorpheraty/d3-barchart-example
I am going to assume you are already familiar with the basic concepts of D3 such as selections, scales, and data joins. If not don’t worry, the best way to learn is to tinker with the code and see what happens.
CSV Parsing with React Hooks
To fetch our data we are going to use react hooks and the D3 csv method. Note that the csv method does not automatically infer data types so we will need to iterate over the resulting array and manually type gdp as an integer.
Tooltips can be a great way to display additional data dimensions in your visualizations. Since D3 relies on common web standards (HTML, SVG, and CSS), we can create bespoke tooltips without having to learn any proprietary frameworks.
Let’s start by creating a d3 selection object that we will name tooltip. First select body of the DOM as our node of which we append a div element. Next we will chain the .attr method to add a css class. Note that since we do not want to display the tooltip unless the mouseover condition is met, we set the visibility property to hidden.
To create shapes that correspond to our data points in D3 you need to understand data joins.
This sequence of methods can be confusing for beginners to D3. I recommend console logging at each step in the method chain to understand what is actually happening.
1. The first method returns a new empty selection of rects, with the grouped svg object (g) as the parent node.
2. The second method links our data to the empty array and results in three different possible states: enter, update, and exit. The enter selection now contains enterNodes which act as a placeholder for new datum. When we call the enter method, the amount of possible states will be reduced to just enter.
3. Lastly, the .append(“rect”) method appends a rectangle for each data point in the SVG container.
D3 has many built-in event handlers that can help make your visualizations more interactive. For our chart, we want our tooltip selection that we created above to become visibile and to display the gdp for each respective country. To do this, we will chain event handlers to our rect selection with the .on() method.
There are three event handlers used to render the tooltip — mouseover, mousemove, and mouseout. The mouseover and mouseout event handlers toggle the visibility of the tooltip. The mousemove event handler determines the location of the cursors using event.pageY and event.pageX and positions the tooltip down and to the right. We then add html to populate the tooltip with data.
The chief allure of D3 is that it is endlessly customizable and gives you the tools to do visualize data in unique and interesting ways. A big thanks to Mike Bostock for creating such an incredible tool!