I’m doing some form of data visualization learning for 180 days because I need to #JFDI. See post explaining how and why I’m doing this.
Code Learning:
Chapter 8: Axes Interactive Data Visualization for the Web
*Read through this earlier, but clearly had no deep understanding until now.
Three Takeaways:
- D3’s axes are actually functions whose parameters you define. Unlike scales, when an axis function is called, it doesn’t return a value, but generates the visual elements of the axis, including lines, labels, and ticks. At a minimum, each axis also needs to be told on what scale to operate.
-
xAxis.scale(xScale); -
svg.append("g").call(xAxis); - You might be wondering why this looks so different from our friendly scale functions. Here’s why: because an axis function actually draws something to the screen (by appending SVG elements to the DOM), we need to specify where in the DOM it should place those new elements. This is in contrast to scale functions like
xScale(), for example, which calculate a value and return those values, typically for use by yet another function, without impacting the DOM at all.- So what we’re doing with the preceding code is to first reference
svg, the SVG image in the DOM. Then, weappend()a newgelement to the end of the SVG. In SVG land, agelement is a group element. Group elements are invisible, unlikeline,rect, andcircle, and they have no visual presence themselves. Yet they help us in two ways: first,gelements can be used to contain (or “group”) other elements, which keeps our code nice and tidy. Second, we can apply transformations togelements, which affects how visual elements within that group (such aslines,rects, andcircles) are rendered. - So we’ve created a new
g, and then finally, the functioncall()is called on our newg. So what iscall(), and who is it calling?D3’scall()function takes the incoming selection, as received from the prior link in the chain, and hands that selection off to any function. In this case, the selection is our newggroup element. Although thegisn’t strictly necessary, we are using it because the axis function is about to generate lots of crazy lines and numbers, and it’s nice to contain all those elements within a single group object.call()hands offgto thexAxisfunction, so our axis is generated withing.
- So what we’re doing with the preceding code is to first reference
- “You might notice that when we use CSS rules to style SVG elements, only SVG attribute names—not regular CSS properties—should be used. This is confusing, because many properties share the same names in both CSS and SVG, but some do not. eg. color versus fill. If you ever find yourself trying to style SVG elements, but for some reason the stupid CSS code just isn’t working, I suggest you take a deep breath, pause, and then review your property names very closely to ensure you’re using SVG names, not CSS ones. “
Leave a Reply