I\'m using SVG and D3 to create bar graphs and have a question concerning how to color them. I\'ve searched many questions on this site and others and haven\'t yet found any
This is simple to implement but a bit hard to grasp, you need to specify that the gradient units are userSpaceOnUse
and then define the region where you want it to apply through x1
, x2
, y1
, y2
:
var gradient = svg
.append("linearGradient")
.attr("y1", minY)
.attr("y2", maxY)
.attr("x1", "0")
.attr("x2", "0")
.attr("id", "gradient")
.attr("gradientUnits", "userSpaceOnUse")
gradient
.append("stop")
.attr("offset", "0")
.attr("stop-color", "#ff0")
gradient
.append("stop")
.attr("offset", "0.5")
.attr("stop-color", "#f00")
You can see a demo here: http://jsfiddle.net/ZCwrx/