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>
 </body>
</html>

CSS

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 data_array = new Array(),
    x_scale = new Object(),
    y_scale = new Object();


/********* Runtime execution ***********/

setupDataAndScales();
setupPlot();
drawData();

/******** 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','blue');
}

//setup the structure and layout of the svg object
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('class','unclipped-area')  
           .attr('transform' , 'translate(' + //x_offset, y_offset             
             ir_x_offset + ',' + ir_y_offset + 
             ')')     
      .append('g')        
        .attr('class','clipped-area')    ...