Skip to content

Instantly share code, notes, and snippets.

@onetwothreebutter
Last active January 4, 2018 14:34
Show Gist options
  • Save onetwothreebutter/46c2a9f8eae561fa464397b73d86ba03 to your computer and use it in GitHub Desktop.
Save onetwothreebutter/46c2a9f8eae561fa464397b73d86ba03 to your computer and use it in GitHub Desktop.
fresh block
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>
// Feel free to change or delete any of the code you see in this editor!
var width = 960;
var height = 600;
var margin = {left: 50, right:50, top:50, bottom:50};
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("border", "1px solid gray");
var data = [{
race: 'White',
number: '129209'
},
{
race: 'Black',
number: '45'
},
{
race: 'Asian',
number: '129'
},
{
race: 'Hawaiian/Pac Island',
number: '9'
},
{
race: 'Hispanic',
number: '584'
},
{
race: 'Native American',
number: '97'
},
{
race: 'Multi-racial',
number: '155'
},
];
data.forEach(function(d){
d.number = Number(d.number);
});
//create the xAxis
var races = data.map(d=>d.race);
var xScale = d3.scaleBand()
.domain(races)
.range([0,width]);
var xAxis = d3.axisBottom(xScale);
svg.append('g')
.attr('transform', 'translate(' + [margin.left, height-margin.bottom] + ')')
.call(xAxis);
//create the yAxis for White Farmers
var numWhiteFarmers = data.filter(d=>d.race=='White').map(d=>d.number);
var maxWhiteFarmers = d3.max(numWhiteFarmers);
var whiteFarmerAxisPortion = 1/5;
var yScaleWhite = d3.scaleLinear()
.domain([maxWhiteFarmers-10000, maxWhiteFarmers+10000])
.range([height*whiteFarmerAxisPortion, 0])
.clamp(true);
var yAxisWhite = d3.axisLeft(yScaleWhite).ticks(4);
svg.append('g')
.attr('transform', 'translate(' +[margin.left, height*whiteFarmerAxisPortion] + ')')
.call(yAxisWhite);
//create yAxis for Other Races
var otherFarmers =
data.filter(d=>d.race!='White').map(d=>d.number);
var maxOtherFarmers = d3.max(otherFarmers);
var otherFarmerAxisPortion = 4/5;
var yScaleOther = d3.scaleLinear()
.domain([0,maxOtherFarmers])
.range([height*otherFarmerAxisPortion, 200])
.clamp(true);
var yAxisOther = d3.axisLeft(yScaleOther).ticks(5);
svg.append('g')
.attr('transform', 'translate(' +[margin.left, height*otherFarmerAxisPortion-420] + ')')
.call(yAxisOther);
//add the data
svg.append('g')
.attr('transform', 'translate('+ [margin.left, margin.top]+')')
.selectAll('rect.lower')
.data(data).enter()
.append('rect')
.attr('x',d=>margin.left + xScale(d.race))
.attr('y',d=>yScaleOther(d.number))
.attr('width', 10)
.attr('height', d=>(otherFarmerAxisPortion*height - yScaleOther(d.number)));
console.log(yScaleWhite.domain());
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment