Skip to main content

D3 Visualization with Vue.js : a powerful alliance (when done right!)

[UPDATED MAY 2022]  D3.js is a very powerful visualization tool, especially for specialized/custom needs...  On the flip side, it's rather hard to use - with a steep learning curve.

Even worse if one also wants interactivity!

But why is D3 so hard/clunky to use?  And what can be done about it?

Spoiler alert: Vue.js (or other modern front-end framework) to the rescue - if done right...

All code in the examples is available in this GitHub repository.

The Root of the Problem

In a nutshell, what makes D3 awkward to use is that, for historical reasons, it tries to do too much: most painfully, it uses an old way to do direct DOM manipulation (i.e. restructuring the page layout) - an operation that nowadays is superbly handled in a far more friendly way by modern front-end frameworks, such as Vue.js

Document Object Model (DOM) is a programming interface for web documents.  In simple terms, it's the structure of the elements on a web page (text, images, etc.)
Let the front-end framework (such as Vue) handle it!

D3 is more than just about data visualization.  As a consequence of D3 emerging before modern front-end frameworks, it had to "do it all" itself.  As a result, it consists of several parts:

  • DOM utilities: this part resembles the archaic jQuery, and absolutely does not belong in modern web pages!
  • Data utilities/analysis: fine, but also available through other libraries, such as Lodash
  • Data visualization: this is the key "good part" that we must tap into!
  • Animation

For more detail, an excellent in-depth article:  D3 is not a Data Visualization Library.

From "D3 is not a Data Visualization Library",
by Elijah Meeks
The author, Elijah Meeks, who also wrote a D3 book, introduces diagrams such as this:

and then goes into a good amount of detail about each of the parts.

The take-home messages is the appealing prospect to "choose which parts of the [D3] library to learn and which parts to avoid".

But how exactly does one do that, in actual practice?

The Broad Picture

Anyone who's looking into creating custom D3 visualizations - as opposed to just picking a boiler-plate one from the vast D3 offerings (such as these) - is clearly someone with very specific/specialized needs.  Someone who also probably needs interactivity, reactivity to changes in the data, and generally fine control over the front end.  In short, a front-end programmer... or someone in a team that involves front-end programmers who are already using Vue.js or React, or another modern front-end framework.  If your visualization needs are common and straightforward, you're in the wrong place!

Below, I will discuss in detail how to graft the "good parts" of D3 into the "scaffold" provided by Vue.  A similar approach will probably work for other front-end frameworks.

A Warm-Up Example

The awkward "retro" quality of D3, when it's used to do it all, becomes painfully aware to anyone accustomed to a modern front-end framework.  When - in addition to the graphing part - D3 tries to also manage user interactivity or some type of UI, it feels like a journey to the painful ol' days of jQuery (an early JavaScript library to manage the front end.)

Bar graph and a checkbox UI,
all handled by D3

For example, an excellent in-depth first intro to D3 is a 3-part video series from 2020: all is good in the 1st and 2nd videos, which introduce making a bar graph with D3...  

but in the final part, where the checkbox interactivity is added, ouch!  It's painfully to revisit the old ways of doing such things prior to modern front-end frameworks.  With minor tweaks I added, here's the code for this "test3" : HMTL (largely a placeholder, plus CSS) and the D3 JavaScript file, where most of the action takes place.

In the first part of the JS file, you can see D3 reaching into the DOM (a task that really belongs to the framework) in lines such as   d3.select('svg')   , which is reminiscent of the old jQuery world.  The pain further increases in the 2nd half of the file, with the clunky pre-frameworks way of managing the UI!

In my test2 (files) I have a simpler example, with a bar graph but no checkboxes; much less awkward, when we're not trying to use D3 for the UI...

The even simpler test1 (files) has no "real" graphics (SVG code) at all: it emphasizes how D3 can be used - in a "retro" programming fashion - for any sort of general DOM manipulation.

SVG stands for Scalable Vector Graphics.  In simple terms, it's the counterpart of HML tags for graphics elements, such as rectangles, lines and points.  A good, detailed tutorial.
What D3 does is to generate the SVG code, and stick it in the right places on the page (this last function is best left to the front-end framework!)

How to keep the "good" D3 and ditch the "archaic" D3

I researched using Vue with D3...  and found that many authors utilize a very weak integration of the two: a simple insertion of the D3 elements into a Vue page - which completely fails to return the control of the DOM to Vue... and generally leads to unreactive pages (i.e. not automatically changing with changes of the underlying Vue data), unless special remedies are taken, such as the implementation of "watch" functions in Vue.

I also came across a good but long-winded workshop, plus some articles that I found helpful but confusing (such as this one), and rare truly helpful articles like this one (which I'll revisit at the very end)... but mostly I found rehashes of the half-baked minimal integrations of D3 into Vue pages.

I ended up creating a series of code snapshots of a step-by-step process I took, to start with pure D3 ("I do it all, even what I don't do well"), and gradually wrestle away from D3 the parts that best belong to Vue - with the final result of a clean, easy-to-read (if you know Vue!) and reactive modern front end, with a sensible division of labor between D3 and Vue; in principle it could also be any other modern front-end framework.

A STEP-BY-STEP example: a D3 heatmap gradually turned into a clean D3 + Vue

FILES: in the repository, check out the files "heatmap1.htm" thru "heatmap8.htm", plus their .js counterparts when present, in the heatmap directory.

Not a Vue expert?  No problem - you can simply clone the repository to your local machine, and open the HTML files in your browser: NOTHING TO INSTALL :)

1) heatmap1.htm is a pure D3 heatmap, taken straight out from this D3 graph gallery.

2) In heatmap2.htm, I add the Vue scaffold (a "root" element that I'm not yet using), and I replace the heatmap dataset with just a handful of values hardwired into the file.
Please note that I use the final release (2.6) of Vue version 2, stored in my repository.

3) In heatmap3.htm, I introduce a Vue component, <vue-heatmap-3> , in the file heatmap3_comp.js.  All the data for the heatmap is now managed by Vue, and passed to the component, but the heatmap is still entirely produced, and inserted into the DOM, by D3.

The Vue component receives data from its parent, but is NOT reactive:  the mounted() function gets called once, and that's the end of it!

(Note: I use the "template literals" format for Vue components, which I think is very readable, and requires no file compilation.  Various alternatives are discussed in this excellent article: 7 Ways to Define a Component Template in Vue.js)

Many authors stop here in their weak integration of D3 and Vue...  but this surely isn't the end of the story!

4) In heatmap4 (.htm and .js files), a different Vue component takes control of computed values and of most functions used by the original D3 code, except for the axes generation.  

Vue takes control, but does not re-invent the wheel: it invokes the amazing functions provided by D3 libraries, for example for scaling or color mapping.

The DOM manipulation is still being done by D3, for now.
Why are we leaving the axes for last?  Because, alas, the creation of the axes in D3 is hopelessly entangled with the DOM modification, rather than being a truly modular element that just produces the SVG code for the axes without messing around with the DOM...

5) In heatmap5, the creation of the actual heatmap is separated from the creation of the overall graph and axes.  Also, a Vue watch is instituted for the prop 'my_data', which now becomes reactive: it changes the heatmap as needed, when the data is modified.

The screenshot below was taken using the (highly, highly recommended!) Vue Devtools extension, seen here in Firefox.  If you change the "my_data" array in the Vue root component, you'll see the heatmap instantly change.  (Note: make sure to edit the whole array, as show near the bottom of the picture; if you expand the arrow next to my_data, and just change one array element, Vue doesn't detect that.)

By contrast, if you make a similar change in the previous heatmap4, nothing happens, because it's not reactive.  Note that we have to do extra work to attain reactivity; that's because D3 is still meddling with the DOM.  

Reactivity will happen organically once we banish D3 from getting its dirty little paws directly into the DOM.

6) In heatmap6, Vue takes control of the SVG element (in the template of the Vue component), while D3 handles the CONTENTS of the SVG element.

7) In heatmap7, most of the plot is now handled directly by Vue, in an SVG code template (very easy to read and modify), using Vue iteration over the heatmap rectangles, and Vue computations of plot parameters with D3 libraries.

Many D3 libraries are awesome, and we're continuing to utilize them, while at the same time banishing the archaic part of D3


The axes still remain a DOM manipulation directly done by D3, and require special handling to be reactive to changes in the data (while the Vue-controlled part is automatically reactive.)

8) In heatmap8, the last direct DOM manipulation has been wrestled out of D3, hallelujah!

As mentioned earlier, the D3 axes generator is hopelessly entangled with the DOM manipulation, and therefore has to be ditched.  

It's pretty easy, however, to create an SVG axes generator; I ported to JavaScript an old SVG axes generator I had created in PHP many years ago, and tweaked it to give almost identical visuals to the built-in one in D3 (I changed the axes to grey, but you can tweak that and more in the CSS, which I have in the html file.)  The code can be found in the SVG_helper library; with just a light knowledge of SVG, one can easily tweak it, to get the axes any way one wants them, or to factor out to convenient JavaScript calls any other custom SVG code that one needs.

The heatmap also includes a few extra lines (middle, top and right), to demonstrate various ways of adding SVG elements in the template of the Vue component.

All the extra code to create reactivity is now taken out: the page is organically reactive because it utilizes Vue correctly - rather than the earlier "backseat driving" by D3!

Here's an example of reactivity to the enlargement of "outer_width":

All Said and Done...

The final result (files heatmap8.htm and heatmap8_comp.js) utilizes standard D3 libraries for scaling and color mapping, plus a simple SVG helper library (just for the axes) that could be easily customized to one's very specific needs.

[May 2022 update: an improved SVG helper library is now being expanded and maintained by the open-source project Life123; details at the very end of this article!]

Is it simpler than the starting point (heatmap1.htm)?  Well, if one was aiming to do nothing more than the heatmap per se, then the original D3 implementation, or the light Vue integration from step3, might be just fine.

But here I've been addressing the needs of people who have to go beyond existing boiler-plate solutions, and require a high level of control of the graphics as well as the UI surrounding it.  

The original pure-D3 heatmap is OK as a standalone element, but the final heatmap8 in our example above is fully reactive to changes in the data, and is completely in Vue's control, with the SVG very accessible in template form - and so, it's very ready to be easily expanded with UI controls, interactivity and customization, with just a normal Vue skillset, plus a light knowledge of SVG and of the needed D3 libraries.  Anything not provided by a standard D3 library, could be custom-designed and added to the SVG helper library.

D3 at the service of the front-end framework!
Reaping the Benefits

Now that we have a full integration of the heatmap graphics with Vue, we can easily add all sorts of UI controls and interactivity: we're in "Vue territory" and we can draw upon its power and convenience.  

For example, it's a breeze to add a slider that lets the user select a start bin to display in the heatmap.  I'm calling the file heatmap8_slider.htm, rather than heatmap9, for clarity - because we're still using the same Vue component (heatmap8_comp.js) to draw the actual heatmap.  I also added more data to better see the effect, and I'm showing the raw data - being sent to the graphing component - under the image.

Two More Examples

Having discussed the step-by-step process to wrestle out of D3 what is best done by the front-end framework, here are two more complete examples of D3 fully and sensibly integrated into Vue:

1) Dots and lines.  A button toggles between styles.  It looks best on Chrome.  Code.

Based on this video.

 

2) An "interactive star".  A slider determines the number of rays.  Code.

Adapted from this very helpful detailed article.


See More

[May 2022 update]  The open-source project Life123 is exactly an example of something that needs interactive, very customized ad-hoc visualization. You'll find a growing list of Vue components using D3 libraries in the repository for that project: GitHub directory with Vue components, their CSS files and HTML test files. 

Maybe get involved in contributing Vue/D3 components for that open source project?

Comments

Popular posts from this blog

Graph Databases (Neo4j) - a revolution in modeling the real world!

(UPDATED 9/2022) - I was "married" to Relational Databases for many years... and it was a good "relationship" full of love and productivity - but SOMETHING WAS MISSING! Let me backtrack.   In college, I got a hint of the "pre-relational database" days...  Mercifully, that was largely before my time, but  - primarily through a class - I got a taste of what the world was like before relational databases.  It's an understatement to say: YUCK! Gratitude for the power and convenience of Relational Databases and SQL - and relief at having narrowly averted life before it! - made me an instant mega-fan of that technology.  And for many years I held various jobs that, directly or indirectly, made use of MySQL and other relational databases - whether as a Database Administrator, Full-Stack Developer, Data Scientist, CTO or various other roles. But there were thorns in the otherwise happy relationship The root cause: THE REAL WORLD DOES NOT REALLY RESEMBLE THE

A "Seismic Shift" in Longevity Science : Mainstream Acceptance + Large Funding

"You are incredibly prescient!"   I woke up to those words from a former colleague on Jan. 19, 2022: the bombshell announcement that the Chief Science Officer of pharma giant GSK, where I worked until recently, will become the CEO at the new, $3 BILLION longevity science company Altos (presumably also funded by Amazon's Jeff Bezos.) Big Pharma is at long last embracing Longevity Science. The corollary: longevity science is entering Mainstream (with capital "M") But let me backtrack... The Decade of Longevity Science When Harvard professor David Sinclair declared the 2020's to be the " decade of the paradigm shift about age reversal ", one could perhaps be dismissive of it as just an outburst of enthusiasm... But in the past couple of years, we're seeing strong evidence that his forecast is right on the mark! While I worked at GlaxoSmithKline - a giant, top-10, pharma company - I vigorously advocated forming a Longevity Science dept., and sp

Life123 : Quantitative Modeling of Biological Systems

(UPDATED 8/2022) - Are we ready to embark on a next-generation detailed quantitative modeling of complex biological systems , including whole-cell simulations?  An anticipated up-jump in computing power may be imminent from Photonics computers (which I discuss here ), and GPU's are rapidly gaining power as well...  Are we in ready state to put existing - and upcoming - power to good use? This is a manifest, and a call to action What's Life123? It's about detailed quantitative modeling of biological systems in 1-D, 2-D and full 3-D, as well as a multi-faceted software platform for doing so. What's (pseudo-)1D?  For now, let's say it's like the inside of a long, thin tube - with no interactions with the tube.  Likewise, (pseudo-)2D can be thought of as a Petri dish, with no interactions with the lid or the bottom. Website : https://life123.science A purposeful decision to also utilize 1D and 2D But why?  Yes, it's in part about "walk before you run&quo

Online Courses: (Often) Free and Just Awesome!

“Education is the kindling of a flame, not the filling of a vessel.” -Socrates.  [UPDATED Mar. 2021] Acquiring knowledge has been a hobby of mine since 4th grade, so it's no surprise that I'm the proverbial "kid in the candy store" when it comes to online courses!   As of writing, I have followed over 20 so far, and trying to decide what the next one will be... Utopia or Dystopia? You ever find yourself imagining the future, and wondering whether it'll turn out to be “utopian” or “dystopian”? Well, the state of higher education in the United States is decisively dystopian , with its absurdly ballooned costs and runaway student loans (a “bubble” that may burst sooner or later, mark my words!),  BUT there’s a counterpoint that is decisively utopian , namely the explosive rise of free online courses 😊 Here’s a brief 2012 Ted talk about the rise of free online courses , dated but still of interest. The gist of that TED talk is that online learning has com

Multimedia Knowledge Representation and Management : "Brain Annex"

 (Updated Feb. 2022) Wouldn't it be fantastic to have a "butler" to help us as we constantly face drowning in information? That need was crushingly pressing for me , as a polymath with a thirst for knowledge in several fields, not to mention numerous very technical jobs over the years, several complex research projects, old notes from college and grad school, an endless stream of online courses I take , a tech startup I founded and used to run, the many conferences I attend, life in general, and even hobbies that tend to generate abundant information (such as flying airplanes and studying multiple foreign languages!)   I was immensely eager for some sort of powerful assistance, something so helpful that I could poetically describe as an " annex " to my brain.. In this blog entry, I'll describe how deep frustration with existing software tools led to the start of the open-source BrainAnnex.org project, a web-based knowledge representation and manageme

Anti-Aging Research: Science, not Hype

Last updated November 2021 Q: "How is aging a disease?" A: "It's a dynamic system that veers away from its homeostasis (normal equilibrium point): hence a form of slow-progressing illness. Labeling it as 'natural' is a surrender to our traditional state of ignorance and powerlessness, which fortunately is beginning to be changed!" The above is my standard answer to an oft-asked question. The science of aging is by all evidence very misunderstood by the general public.  Hype, misinformation and unquestioned assumptions often prevail, unfortunately. Aging as a systemic breakdown of the body, rather than a series of isolated events and conditions. This 2013 diagram from NIH is a good way to jump-start contemplating the big picture: The diagram originates from the Cell journal: The Hallmarks of Aging   Telomere shortening is perhaps the one most talked about - but just one of several processes.  As stated in the above paper: Each

Interactomics + Super (or Quantum) Computers + Machine Learning : the Future of Medicine?

[Updated Mar. 2021] Interactomics today bears a certain resemblance to genomics in the  1990s...  Big gaps in knowledge, but an explosively-growing field of great promise. If you're unfamiliar with the terms, genomics is about deciphering the gene sequence of an organism, while interactomics is about describing all the relevant bio-molecules and their web of interactions. A Detective Story Think of a good police-detective story; typically there is a multitude of characters, and an impossible-to-remember number of relationships: A hates B, who loves C, who had a crush on D, who always steers clear of E, who was best friends with A until D arrived... Yes, just like those detective stories, things get very complex with our biological story!  Examples of webs of interactions, familiar to many who took intro biology, are the Krebs cycle for metabolism or the Calvin cycle to fix carbon into sugars in plant photosynthesis. Now, imagine vastly expanding those cycles of rea

Brain Microarchitecture : Feedback from Higher-order areas to Lower-order areas

Some questions that arise in Machine Learning involve the prospect of using feedback from Higher-order areas (downstream) to Lower-order areas (upstream), and using Global Knowledge for Local Processing.  A desire to gain insight into those issues from Neuroscience ("how does the brain do it?") led me to some fascinating investigations into the Microcircuits of the Cerebral Cortex.  This blog entry is a broad review of the field, in the context of the original motivating questions from Machine Learning.   Starting out with a quote from the “bible of Neuroscience”: From Principles of Neural Science, 5th edn  (Online book location 1435.3 / 5867).  Emphasis and note added by me: Sensory pathways are not exclusively serial; in each functional pathway higher-order areas project back to the lower-order areas from which they receive input. In this way neurons in higher-order areas, sensitive to the global pattern of sensory input, can modulate the activity of neurons in lowe

Photonic Computer - a "supercharged GPU" with very low energy consumption

Yes, we all wish for Quantum Computers... but in the meantime we need something here and now!  Could Photonic Computers fit that role? Just about everyone has heard of fiber optics – using light for data transmission – but did you know that light can also be used for computing? There's a new commercial product expected for early next year (2022) . I contacted the CEO, Nicholas Harris, of a 4-y.o. startup, Lightmatter , interviewed in April 2021 here . Photonic computers, at least in their first commercial appearance, are essentially accelerator cards for Linear Algebra - and so of special interest for Machine Learning and some types of simulations.    Their claims are remarkable: 10X faster than some of the best GPUs using 90% less energy can be used with existing software stacks, such as TensorFlow commercially available early next year (2022) a lot of future growth, as additional wavelengths of light get used in parallel My own interest is pr