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'>
</div>
</div>
</body>
</html>
CSS
.data_line {
fill: none;
stroke: #355;
stroke-width:2;
}
.x_axis line, .x_axis path, .y_axis line, .y_axis path {
fill: none;
stroke: #222;
stroke-width: 1;
stroke-opacity: 0.5;
}
svg circle {
stroke: none;
fill: blue;
}
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';
}
#start_data_stream {
font-size:16px;
}
#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 data_array = new Array(),
x_scale = new Object(),
y_scale = new Object(),
z_color_scale = new Object();
/********* Runtime execution ***********/
setupDataAndScales();
setupPlot();
drawData();
/******** Functions below!*************/
function setupPlot() {
//calculate the position of the inner plot area
var ir_x_offset = w * (( 1- inner_rectangle_ratio) / 2),
ir_y_offset = h * (( 1- inner_rectangle_ratio) / 2);
//attach an svg object to the DOM. Size it appropriately
var svg = d3.select('#plot')
.append('svg:svg')
.attr('width', w)
.attr('height', h);
//draw an outer border. Not a great design choice.
svg.append('rect')
.attr('x', '0')
.attr('y', '0')
.attr('width', w)
.attr('height', h)
.attr('stroke-width', '2')
.attr('stroke', 'black')
.attr('fill', 'none');
//the plot area is inset from the border
svg.append('g')
.attr('transform' , 'translate(' + //x_offset, y_offset
ir_x_offset + ',' + ir_y_offset +
')')
.append('g')
.attr('class','clipped-area')
.attr("clip-path", "url(#clip)"); //attach clip
d3.select('.clipped-area')
.append('g')
.attr('class','data_plot');
d3.select('.data_plot')
.append('g')
.attr('class','line_plot');
d3.select('.data_plot')
.append('g')
.attr('class','scatter_plot');
//attach a title to the graph using a svg:text object
svg.append('text')
.attr('class', 'title')
.attr('x', w/2 - 40)//position in the center (sorta)
.attr('y', "14")
.text('Scatter Plot!');
}
//setup the global variables: data +...