Data without visualization is dull. This is particularly true for changing data. We seem to be much better at noticing moving things than we are at noticing changes between spreadsheet cells or other text. That’s okay. I’m actually a big fan of that. Text does not usually threaten to run me over when I attempt to cross a street. So let’s create moving things with D3.js and drive the animation reactively with data from a server written in Scala using the Play Framework.
Creating the animated barchart is a little more involved. Let us start with something really simple today. Luckily I have a problem to solve that calls for a simple animation: sse-perf when running might or might not have have established connections hitting a server. If it does, it becomes immediately obvious that the connection to the sse-perf server is alive because the bars are animated. What if there are no client connections and thus there is nothing to report except zero values? I can have these zeros fly into the chart instead of the bars, but that looks really awful, I’ve tried it. But without anything moving, the connection looks dead. What do I do?
How about a visual heartbeat? Just a simple red dot that gets bigger when a new Server Sent Event is received and then shrinks to normal size again. This succeeds in convincing me that what I am looking at is still alive:
Let’s implement that and drive it by a Server Sent Event stream. First of all, we need a div that will hold our animation which we can style and position by css however we like:
1 2 3 4
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
We draw the dot first. Using the global d3 object, we select our #heartbeat div, append an svg of size 20px by 20px, append a circle at x=10px, y=10px, give it a radius of 3px and fill it red. Thanks to method chaining, the D3 code almost reads like prose.
We then establish an EventSource(“/metricsFeed”) connection to the metrics feed and assign a handler function as an event listener to the “message” event. See the stream for yourself. We can use the handler function to trigger the animation.
Once again, the D3 code reads like a sentence: using the heartbeat object created above, we transition the radius from the initial 3px to 7px, to 3px, to 6px and back to 3px, all of these with a duration of 700ms each.
The stream I use as a trigger has data every 3 seconds. I found that it looks unhealthy if the heartbeat only animates 20 times a second, so I do the expansion / contraction cycle twice on each event. D3.js is great; it has a bit of a learning curve but it is well worth it because it will give you full control over everything you could possibly want to tweak on your page.
This is it for today, check back for more elaborate examples in the future. If you haven’t already, how about you subscribe to the mailing list so you won’t miss anything?