This is a graph demonstrating the implimentation of a gradient on an area graph. This was written using d3.js v4 and is a follow on to the gradient line graph example here.
This graph is part of the code samples for the update to the book D3 Tips and Tricks to version 4 of d3.js.
forked from d3noob's block: Area graph with gradient in v4
forked from fogonwater's block: Area graph with gradient in v4
xxxxxxxxxx
<meta charset="utf-8">
<style> /* set the CSS */
body {text-align:center}
svg { font-family: Courier; }
</style>
<body>
<svg width="960" height="160">
<text class="title" x=10 y=50></text>
<g transform="translate(1,1)"></g>
</svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js"></script>
<script>
const start = moment("2007-01-15"),
end = moment("2017-12-10"),
num_days = end.diff(start, "days") - 1
// set the dimensions and margins of the graph
const svg = d3.select("svg"),
width = +svg.attr("width"),
height= +svg.attr("height")
// parse the date / time
var parseTime = d3.timeParse("%Y-%m-%d");
// set the ranges
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
// Get the data
d3.csv("data.csv", function(error, raw) {
var data = []
// format the data
raw.forEach(function(d) {
if (d.NZDI_INDICATOR == 'NZDI' && +d.VAL > 0.1) {
d.date = parseTime(d.OBS_DATE)
d.value = +d.VAL
data.push(d)
}
})
raw = null
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }))
y.domain([0, d3.max(data, function(d) { return d.value; })])
var color = d3.scaleSequential(d3.interpolateYlOrBr)
.domain([0,2.5])
svg.selectAll("bar")
.data(data)
.enter().append("rect")
.style("fill", function(d) { return color(d.value); })
.attr("x", function(d) { return x(d.date); })
.attr("width", (width / num_days) + 0.4)
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value) })
svg.append("text")
.text(function(d) {return data.length + ' elements (' + data.length / raw.length + '%)'})
.attr("y", 50)
.attr("x", 10)
.attr("font-size", 12)
.attr("font-family", "monospace")
});
</script>
</body>
https://d3js.org/d3.v4.min.js
https://d3js.org/d3-scale-chromatic.v1.min.js
https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.4/moment.min.js