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 .plot-area {
    overflow: hidden;
}

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;

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

setupDataAndScales();
setupPlot();

/******** Functions below!*************/

function setupPlot() {
      
//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');        
 
    //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 + positional and color scales
function setupDataAndScales() {

    data_array = [  //inital set of random data. we could generate this 
        {z:32, y:472}, //functionally, instead
        {z:47, y:593},
        {z:83, y:32},
        {z:47, y:492},
        {z:4, y:192},
        {z:19, y:321},
        {z:32, y:871},
        {z:67, y:392},
        {z:88, y:313},
        {z:71, y:592},
        {z:55, y:392},
        {z:30, y:230},
        {z:4, y:721},
        {z:13, y:482},
        {z:24, y:10},
        {z:21, y:874},
        {z:42, y:239},
        {z:49, y:752},
        {z:84, y:83},
        {z:29, y:128},
        {z:92, y:902},
    ];

}