Skip to content

Instantly share code, notes, and snippets.

@boyets
Created April 10, 2018 22:48
Show Gist options
  • Save boyets/ba6e1b674622ae4002f442309fc046cf to your computer and use it in GitHub Desktop.
Save boyets/ba6e1b674622ae4002f442309fc046cf to your computer and use it in GitHub Desktop.
Test
license: mit
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
body { margin:0;position:fixed;top:0;right:0;bottom:0;left:0; }
</style>
</head>
<body>
<script>
var data = [
{
leg:[{id:16, data:{value:'Bar 1', key:'Bar 1 Test'}}],
fdata: [{id: 100, data:[{value: 20.646838}]}, {id: 200, data:[{value: 742.261986}]}]
},
{
leg:[{id:16, data:{value:'Bar 2', key:'Bar 2 Test'}}],
fdata: [{id: 100, data:[{value: 48.403265}]}, {id: 200, data:[{value: 149.444294}]}]
},
{
leg:[{id:16, data:{value:'Bar 3', key:'Bar 3 Test'}}],
fdata: [{id: 100, data:[{value: 25.649341}]}, {id: 200, data:[{value: 76.346227}]}]
},
{
leg:[{id:16, data:{value:'Bar 4', key:'Bar 4 Test'}}],
fdata: [{id: 100, data:[{value: 15.127140}]}, {id: 200, data:[{value: 77.751148}]}]
},
{
leg:[{id:16, data:{value:'Bar 5', key:'Bar 5 Test'}}],
fdata: [{id: 100, data:[{value: 31.600196}]}, {id: 200, data:[{value: 64.787362}]}]
},
{
leg:[{id:16, data:{value:'Bar 6', key:'Bar 6 Test'}}],
fdata: [{id: 100, data:[{value: 5.600196}]}, {id: 200, data:[{value: 64.787362}]}]
}
];
var margin = {top: 30, right: 30, bottom: 30, left: 30},
width = 600,
height = 400;
// important: only use extent if you want min value as your zero in graph
var extent = d3.extent(data, function(d) {
return d.fdata[0].data[0].value;
});
var max = d3.max(data, function(d) {return d.fdata[0].data[0].value})
var xScale = d3
.scaleBand()
.domain(data.map(function(d){ return d.leg[0].data.key; }))
.range([30, width], 0)
.paddingInner([.1])
var yScale = d3
.scaleLinear()
.domain([0, max])
.range([height - 60, 0]);
var xaxis = d3
.axisBottom()
.scale(xScale)
var yaxis = d3
.axisLeft()
.scale(yScale)
var svg = d3
.select('body')
.append('svg')
.attr('width', width)
.attr('height', height)
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
var bars = svg
.selectAll('rect')
.data(data)
.enter()
.append('rect')
.attr('width', function(d) {
return xScale.bandwidth();
})
.attr('x', function(d, i) {
return xScale(d.leg[0].data.key);
})
.attr('y', function(d, i) {
return yScale(d.fdata[0].data[0].value) + 30;
})
.attr('height', function(d, i) {
return height - 60 - yScale(d.fdata[0].data[0].value) ;
})
.attr('fill', 'blue')
svg
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.bottom + ')')
.call(yaxis)
svg
.append('g')
.attr('transform', 'translate(' + 0 + ',' + (height - margin.top) + ')')
.call(xaxis)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment