Using gradient stops and transparency to dynamically fill circle partially in svg using d3js
Using gradient stops and transparency we can fill circle partially in svg. Doing this dynamically using data may be great visualization technique.
You can read my another article which uses the circle over circle and clipping to do similar task here Create filled circle to visualize data using svg.
So, moving on to gradient stops and transparency technique.
First you will require d3.js get it here http://d3js.org/d3.v2.min.js
Here is our Javascript, first create the svg element and define the gradient.
The gradient can take only discrete values to visualize. In this tutorial, we assume the data value is a set of discrete categories like low, medium, medium high, high, extreme etc.
For continuous values like 81 or so you will have to use the other technique of which I shared the link above. Though you won’t have transparencies in your circles you will have to use your bg color to mimic the transparency.
[javascript]
var data = d3.range(30);
var svg = d3.select("body").append("svg");
var minY = 10;
var maxY = 210;
var gradientData = [0, 25, 50, 75, 100];
var gradient = svg
.selectAll("linearGradient")
.data(gradientData)
.enter()
.append("linearGradient")
.attr("y1", "1")
.attr("y2", "0")
.attr("x1", "0")
.attr("x2", "0")
.attr("gradientUnits", "objectBoundingBox")
.attr(‘id’, function(d) {
return "gradient-" + d
});
gradient.append("stop")
.attr("offset", "0")
.attr("stop-opacity", "1")
.attr("stop-color", function(d) {
return "hsl(" + -d * 1.5 + ",50%,50%)";
});
gradient.append("stop")
.attr("offset", function(d) {
return d + "%"
})
.attr("stop-opacity", "1")
.attr("stop-color", function(d) {
return "hsl(" + -d * 1.5 + ",50%,50%)";
});
gradient.append("stop")
.attr("offset", function(d) {
return d + "%"
})
.attr("stop-opacity", "0")
.attr("stop-color", "#fa0");
[/javascript]
Now drawing the circles and using the appropriate gradient to fill them.
[javascript]
svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr(‘opacity’, ‘0.8’)
.attr("cx", function(d) {
return d * 35 + 50
})
.attr("cy", function(d) {
return Math.random() * 250 + 50
}) //randomly positioning the circle
.attr("stroke-width", 1)
.attr("stroke", "hsl(100,50%,50%)")
.attr("r", function(d) {
return Math.random() * 20 + 20
}) // Random radius
.attr("fill", function(d) {
return "url(#gradient-" + (Math.round(Math.random() * 4) * 25) + ")"
});
// I used the random function that will give 0 25 50 75 100 as the value
[/javascript]
I used random values in the radius field and x / y, but you can use these to illustrate some other dimension of your data.
See it working here http://jsfiddle.net/ZCwrx/269/