2013년 9월 29일 일요일

Realtime Streaming Chart using D3.js - 02. Draw a Point

The Code and the Result




Add a button to draw a point on the chart

I want to add a point(circle) on the chart.
So I add <button> in the html, and add a jQuery click event handler, which makes a new data and draw a circle on the chart.


SVG circle

D3 is based on SVG. So the result of the D3 chart consists of SVG tags.
Here I will draw a point using SVG circle, and it look like this:

<circle cx="454" cy="92" r="4" style="fill: #893af5;"></circle>

'cx', 'cy' means the location of the X, Y originated from the Top-Left corner of the SVG.
'r' means the radius of the circle
'style' is just a css style to display the circle.

Our goal is simple.
Produce the HTML code above with our own data.
D3 plays a key role here.


D3 stuff in this code

selection.datum(data)
  selection.datum([value]) returns the selection after binding the value to that selection.
  So using selection.datum(), we can bind our own data to the SVG circle.

selection.attr("cx", function (d) { return xScale(d.x); })
  selection.attr(name, [value]) returns the selection after setting the named attribute with the value. As a value, we can use a function whose arguments are our own data because we bound the data to the selection using datum().


Summary

We drew a point, actually a SVG circle, with our own data using D3's datum() and set the attributes of the element using D3's attr().


What's next?

Now it's time to handle streaming! We are going to stream the axis.

go back | go Next