Multiple D3 Plots on One page
D3 Dabbler Series: Experiences with Angular 2+ and D3 Part 2 of 2
In part 1, I looked at the issue I encountered with the SVG element and the need to increase its size to display the entire D3 plot that was appended to it. This was one of several challenges I faced when trying to integrate D3 into my Angular 6 application. Another issue I encountered was trying to add another plot to the page. It is very likely that one would want to have more than one plot showing on a single page. When adding my second plot, however, things didn’t go as I had hoped. I had not given my SVG element any unique identification and, as a result, the second plot tried to occupy the same space as the first plot. Multiple SVG elements can be appended to the main HTML body, but all should be given a unique ID or appended to a unique element to ensure that each plot on a single page is created in its own space.
For example, if you want to display two plots on the page, the draw plot function for plot one could start as follows, with the plot being appended to an element with ID ‘chart_1’ (note the height, weight and overflow attributes are applied as described in part 1):
let chart_1 = d3.select(“#chart_1”) let svg = chart_1.append(“svg”) .attr(“width”, width) .attr(“height”, height) .attr(“overflow”, “visible”)
And for plot two, the element could have the ID ‘chart_2’:
let chart_2 = d3.select(“#chart_2) let svg = chart_2.append(“svg”) .attr(“width”, width) .attr(“height”, height) .attr(“overflow”, “visible”)
The result of the above ensured that any additional plot that was added took up its own space, provided that a unique ID was used.
Although my D3 journey is still in the very early stages, it is already clear to me that D3 can be used to draw just about anything imaginable and that the limit lies in the capabilities and knowledge of the user. Look out for future “D3 Dabbler” posts where I hope to share more useful things that I learn during my exploration into D3!
Written By Liesl Hendry