xxxxxxxxxx
<html lang="en">
<meta charset="utf-8">
<head>
<title>AS4 Bar Chart</title>
<script src="https://d3js.org/d3.v4.min.js"></script>
<style>
.bars {
fill: rgb(70,130,180);
}
.title {
font-family: sans-serif;
font-size: 20px;
}
.axisLabels {
font-family: sans-serif;
font-size: 14px;
}
</style>
</head>
<body>
<script type="text/javascript">
// declare dimensions
var h = 500,
w = 800,
margin = 100,
axisBuffer = 20;
var xAxisYPos = h-margin,
yAxisXPos = margin-axisBuffer;
// create svg variable
var svg = d3.select("body")
.append("svg")
.attr("height", h)
.attr("width", w);
// load in data
d3.csv("calData.csv", function(dataset) {
// make strings numeric
dataset.forEach(function(d) {
d.ConsumptionCommercialCoal = +d.ConsumptionCommercialCoal;
d.Year = +d.Year;
});
// define scales and axes
var xScale = d3.scaleLinear()
.domain([d3.min(dataset, function(d) { return d.Year;}), d3.max(dataset, function(d) { return d.Year})])
.range([margin, w-margin]),
yScale = d3.scaleLinear()
.domain([d3.min(dataset, function(d) { return d.ConsumptionCommercialCoal;}), Math.ceil((d3.max(dataset, function(d) { return d.ConsumptionCommercialCoal}))/500)*500])
.range([h-margin, margin]),
bandScale = d3.scaleBand()
.domain(d3.range(dataset.length))
.range([margin, w-margin])
.round(true)
.paddingInner(0.05);
var xAxis = d3.axisBottom()
.scale(xScale)
.tickValues(d3.range(d3.min(dataset, function(d) { return d.Year;}), d3.max(dataset, function(d) { return d.Year;}) + 1, 6)) // add 1 to include upper bound
.tickFormat(d3.format("d")),
yAxis = d3.axisLeft()
.scale(yScale);
// draw x axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0, " + xAxisYPos + ")")
.call(xAxis);
// draw y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + yAxisXPos + ", 0)")
.call(yAxis);
// add chart title
svg.append("text")
.text("Commercial Coal Consumption in California by Year")
.attr("class", "title")
.attr("x", w/2)
.attr("y", margin/2)
.attr("text-anchor", "middle");
// add axis labels
svg.append("text")
.attr("class", "axisLabels")
.attr("x", w/2)
.attr("text-anchor", "middle")
.attr("y", h - margin/2)
.text("Year");
svg.append("text")
.attr("class", "axisLabels")
.attr("x", 0)
.attr("y", 0)
.attr("text-anchor", "middle")
.attr("transform", "translate(25, " + h/2 + ")rotate(270)") // translate and rotate y axis label
.text("Commercial Coal Consumption (Billion BTU)");
// draw bars
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("class", "bars")
.attr("x", function(d) {
return xScale(d.Year) - bandScale.bandwidth()/2;
})
.attr("y", function(d) {
return yScale(d.ConsumptionCommercialCoal)
})
.attr("width", function(d) {
return bandScale.bandwidth()
})
.attr("height", function (d) {
return xAxisYPos - yScale(d.ConsumptionCommercialCoal)
});
});
</script>
</body>
https://d3js.org/d3.v4.min.js