Skip to content

Instantly share code, notes, and snippets.

@mukhtyar
Last active January 11, 2018 13:52
Show Gist options
  • Save mukhtyar/f50577e4bad9f522ec8bc0d3500fa1bc to your computer and use it in GitHub Desktop.
Save mukhtyar/f50577e4bad9f522ec8bc0d3500fa1bc to your computer and use it in GitHub Desktop.
Bar Chart using Cal-Adapt data
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.bar {
fill: steelblue;
}
.bar:hover {
fill: brown;
}
.axis--x path {
display: none;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var url = 'http://api.cal-adapt.org/api/series/tasmax_year_livneh/1950-01-01/2005-01-01/?pagesize=100&g=%7B%22type%22%3A%22Point%22%2C%22coordinates%22%3A%5B-121.46875%2C38.59375%5D%7D';
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom;
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1),
y = d3.scaleLinear().rangeRound([height, 0]);
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.json(url, function(error, data) {
if (error) throw error;
var tasmaxData = data.results.map(function(year){
return {
date: year.event,
value: +year.image
};
});
x.domain(tasmaxData.map(function(d) { return d.date; }));
y.domain([0, d3.max(tasmaxData, function(d) {
return d.value;
})]);
g.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
g.append("g")
.attr("class", "axis axis--y")
.call(d3.axisLeft(y).ticks(10))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("FTemperature (degree Celsius)");
g.selectAll(".bar")
.data(tasmaxData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.date); })
.attr("y", function(d) { return y(d.value); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.value); });
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment