Skip to content

Instantly share code, notes, and snippets.

@ne8il
Created March 12, 2013 01:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ne8il/5139408 to your computer and use it in GitHub Desktop.
Save ne8il/5139408 to your computer and use it in GitHub Desktop.
D3 Example 4 : Enter SVG

Recreating our chart, but with SVG-goodness.

<!DOCTYPE html>
<meta charset="utf-8">
<head>
<style>
body {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
width: 960px;
padding:20px;
position: relative;
}
.chartBlock {
}
.namesDiv {
display:inline-block;
position:relative;
height:30px;
line-height:30px;
width:100px;
text-align:center;
}
svg {
padding:20px;
}
.axis path,
.axis line {
fill: none;
stroke: black;
shape-rendering: crispEdges;
}
.axis text {
font-family: sans-serif;
font-size: 11px;
}
</style>
</head>
<body>
</body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var names = [{'name' : 'Frank', 'color' : 'blue', 'weight' : 180},
{'name' : 'Tom', 'color' : 'red', 'weight' : 230},
{'name' : 'Peter', 'color' : 'green', 'weight' : 190},
{'name' : 'Mary', 'color' : 'purple', 'weight' : 150}];
var barWidth = 100,
chartWidth = 400,
chartHeight = 250,
padding = 30;
var svg = d3.select('body')
.append('svg')
.attr('width', chartWidth)
.attr('height', chartHeight);
/** BUILD BLOCKS */
var selection = svg.selectAll('rect')
.data(names);
selection.enter()
.append('rect')
.classed('chartBlock', true)
.style('fill', function(d){
return d['color']
})
.attr('x', function(d, i){
return padding + (i * barWidth);
})
.attr('y', function(d){
return (chartHeight - d['weight'])
})
.attr('height', function(d){
return d['weight'];
})
.attr('width', barWidth);
/** ADD AXIS */
/* Y AXIS */
var min = d3.min(names, function(d){return d['weight']});
var max = d3.max(names, function(d){return d['weight']});
var yScale = d3.scale.linear()
.domain([0, max])
.range([chartHeight, 0]);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left')
.ticks(10);
svg.append("g")
.classed('axis', true)
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
/* X AXIS */
//get array of names for ordinal domain
var nameCats = names.map(function(d){ return d['name']});
var xScale = d3.scale.ordinal()
.domain(nameCats)
.rangeBands([0,chartWidth]);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
svg.append("g")
.classed('axis', true)
.attr('transform', 'translate(' + padding + ', ' + chartHeight + ')')
.call(xAxis);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment