Last updated at Fri, 03 Nov 2017 19:44:29 GMT
In my previous posts I have demonstrated how to combine D3 with AngularJs (wrapping D3 code in Angular’s directives) and how to build effective data visualization with D3. In this post I will focus on building tabular format of data with D3.
Tabular representation of data is often the simplest and clearest way of showing the data to the user. Graphical representations such as Bar chart and Line charts are also effective in communicating the data to the user but Table format can even simplify it.
At Logentries we recently introduced “Table View” for our graphs. Our users can flip between a graphical representation of data and a tabular representation. The table component was built using D3 JS. Initially it may seem a bit strange to build tables with D3, but there is a reason. All of the charts which are currently available in our Dashboards have been built using D3. Those charts are reusable components and they can be used anywhere in the application. This was the main factor why we have chose D3 to build the table, creating a reusable component. Since different charts represent different data views, creating one Table component that would work with all of them became a small challenge. This mostly applies to different types of data such as dates, numbers and strings. To make the Table a reusable component, formatting of the data was crucial. For example Line chart displays data point over time, which is dates. Those dates needed to be formatted correctly. Lets look on how the table is constructed with D3.
- First we need to append the table to the DOM. Since the table takes the place of the chart we need to make sure to remove all previous SVG elements from the DOM.
2. Then we need to append the header row to the Table. As a data attribute we can pass columns, which is an array of column names.
3. Next step is to create a row for each object in the data.
4. Finally the most important step is to create a cell in each row for each column. In each cell we return the column and the actual value. Since values can differ, some being numbers other strings, we need to format the data. We can use a helper function which will do the formatting. The formatting function checks if a passed value is a date, number or a string, then based on that check it returns the formatted value.
One final part is the initialization of the table chart. The Table component takes three arguments id of element, data series and column series.