Skip to content

Instantly share code, notes, and snippets.

@pdebelak
Last active August 29, 2015 14:02
Show Gist options
  • Save pdebelak/2a2cb811b3d38b08acfa to your computer and use it in GitHub Desktop.
Save pdebelak/2a2cb811b3d38b08acfa to your computer and use it in GitHub Desktop.
Example solar panel drawing in D3
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>
</head>
<body>
<script>
// set the height and width of your objects, if they are always the same. I assume this would be the case for a panel at least. You can always hard code it in the data array.
var house = {width: 24, height: 17.5}
var panel = {width: 2.5, height: 5.5}
// set size of you overall svg field. I arbitrarily chose 800 square.
var svg = d3.select('body').append('svg').attr('width', 800).attr('height', 800);
// data as json. x and y set position later
var data = [{x: 15, y: 16, height: house.height, width: house.width, obj: 'house'},
{x: 10, y: 10, height: panel.height, width: panel.width, obj: 'panel' },
{x: 12.5, y: 10, height: panel.height, width: panel.width, obj: 'panel' },
{x: 15, y: 10, height: panel.height, width: panel.width, obj: 'panel' },
{x: 40, y: 40, height: panel.height, width: panel.width, obj: 'panel' }];
// this sets up appropriate scale. I'm not sure what the correct numbers here are, but this turns our measurements in feet into the appropriate number of pixels
var scale = d3.scale.linear()
.domain([0, 50])
.range([0, 800]);
// add a rectangle for each item in data
var rect = svg.selectAll('rect').data(data).enter().append('rect');
// add attributes to the rectangles based on information in data objects, filtered through the scale
rect.attr('x', function(d) {
return scale(d.x);
})
.attr('y', function(d) {
return scale(d.y);
})
.attr('width', function(d) {
return scale(d.width);
})
.attr('height', function(d) {
return scale(d.height);
})
.attr('fill', function(d) {
if (d.obj == 'house') {
return 'blue';
} else if (d.obj == 'panel') {
return 'yellow';
}
})
.attr('stroke', 'orange')
.attr('stroke-width', function(d) {
if (d.obj == 'panel') {
return '1';
} else {
return '0';
}
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment