Skip to content

Instantly share code, notes, and snippets.

@grahampullan
Last active October 21, 2017 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grahampullan/7d2c94e1c08be60b29a72fa8c0b6ff2d to your computer and use it in GitHub Desktop.
Save grahampullan/7d2c94e1c08be60b29a72fa8c0b6ff2d to your computer and use it in GitHub Desktop.
d3 line plot from real time UK Environment Agency river level API
license: mit

A d3 line plot that takes data from the UK Environment Agency river level API. The last 4 weeks from a particular measurement station are shown.

Uses Environment Agency flood and river level data from the real-time data API (Beta).

<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<style>
.line {
fill: none;
stroke: steelblue;
stroke-width: 2px;
}
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var line = d3.line()
.x(function(d) { return x(d3.isoParse(d.dateTime)); })
.y(function(d) { return y(d.value); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
// Fetch data from the UK Environment Agency River Level Real Time API
// Data is from Station "F1902"
// Fetch readings from last 4 weeks
d3.json("https://environment.data.gov.uk/flood-monitoring/id/measures/F1902-level-stage-i-15_min-m/readings?_sorted", function(error, rawData) {
if (error) throw error;
var data=rawData.items;
// Scale the range of the data
x.domain(d3.extent( data, function(d) { return d3.isoParse(d.dateTime); }));
y.domain([0, d3.max( data, function(d) {return d.value;})]);
// Add the line showing the river level
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", line);
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y))
.append("text")
.attr("fill", "#000")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text("River level (m)");
});
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment