Draw an SVG object
by rbkreisberg
HTML
<html>
<head>
<script src="http://mbostock.github.com/d3/d3.js"></script>
</head>
<body>
<div id="container">
<div id="plot">
<!-- the svg object will be inserted here -->
</div>
<br/>
<div class='button_bar'>
<button id="start_data_stream">Start</button>
</div>
</div>
</body>
</html>
CSS
#start_data_stream {
font-size:16px;
}
svg circle {
stroke: none;
fill: blue;
}
.x_axis line, .x_axis path, .y_axis line, .y_axis path {
fill: none;
stroke: #222;
stroke-width: 1;
stroke-opacity: 0.5;
}
svg .plot-area {
overflow: hidden;
}
svg .inner-rect {
stroke-width: 2;
stroke: black;
fill: none
}
svg .title {
stroke: none;
fill: black;
font-weight: bold;
font-size:14px;
font-family:'Helvetica';
}
#plot {
height:300px;
width:450px;
margin-left:20px;
margin-top:20px;
display:block;
}
#container {
width:450px;
text-align:center;
}
JavaScript
//global vars
var w = 450,
h = 300;
var inner_rectangle_ratio = 0.8,
inner_width = inner_rectangle_ratio * w,
inner_height = inner_rectangle_ratio * h;
var paused = true;
var data_array = new Array(),
x_scale = new Object(),
y_scale = new Object(),
z_color_scale = new Object();
var create_line;
/********* Runtime execution ***********/
setupDataAndScales();
setupRendering();
setupPlot();
drawData();
//assign behavior to the button. jQuery is one way to do this
$('#start_data_stream').click(togglePause);
/******** Functions below!*************/
function drawData() {
drawCircles();
}
//attach data to a group of circles
//assign circle position to scaled values
function drawCircles() {
d3.select('.scatter_plot')
.selectAll('.data_point')
.data(data_array)
.enter()
.append('circle') //add the circles
.attr('class','data_point')
.attr('cx',function(point,i) {return x_scale(i);}) //use index as x position
.attr('cy',function(point,i) {return y_scale(point.y);}) //use y property
.attr('r',4)
.style('fill',function(point) {
return z_color_scale(point.z);})
.on('mouseover',function() { //change size and color on mouseover
d3.select(this)
.transition()
.duration(500)
.attr('r',15)
.style('fill','black');
})
.on('mouseout',function() { //restore on mouseout
d3.select(this)
.transition()
.duration(500)
.attr('r',4)
.style('fill',function(point) {
return z_color_scale(point.z);})
});
}
function createDataPoint() {
return {z: Math.floor(Math.random()*100),
y: Math.floor(Math.random() * 1000)};
}
function togglePause() {
//toggle the paused flag
...