How to add drop shadow to d3.js pie or donut chart

matt picture matt · Sep 5, 2012 · Viewed 19.8k times · Source

I am using d3.js to make a simple donut chart.

I'm failing to achieve a drop-shadow or box-shadow effect to add some depth to the chart. I've tried adding the css:

path {
  -moz-box-shadow:    3px 3px 5px 6px #ccc;
  -webkit-box-shadow: 3px 3px 5px 6px #ccc;
  box-shadow:         3px 3px 5px 6px #ccc;
}

To path tags and the g tags, but to no avail. Does anybody know if this is possible with CSS or know of a wordaround of some sort?

Really appreciate the help on such a basic problem. Matt

var data = [0, 35, 65];

var w = 400,
    h = 400,
    r = Math.min(w, h) / 2,
   ir = r * 0.5,
   color = d3.scale.category20(),
   donut = d3.layout.pie().sort(null),
   arc = d3.svg.arc().innerRadius(ir).outerRadius(r);

var svg = d3.select("body").append("svg:svg")
    .attr("width", w)
   .attr("height", h)
.append("svg:g")
   .attr("transform", "translate(" + w / 2 + "," + h / 2 + ")");

var arcs = svg.selectAll("path")
    .data(donut(data))
.enter().append("svg:path")
    .attr("fill", function(d, i) { return color(i); })
    .attr("d", arc);

Answer

reptilicus picture reptilicus · Jun 28, 2013

In case anyone comes across this. . .

 /* For the drop shadow filter... */
  var defs = svg.append("defs");

  var filter = defs.append("filter")
      .attr("id", "dropshadow")

  filter.append("feGaussianBlur")
      .attr("in", "SourceAlpha")
      .attr("stdDeviation", 4)
      .attr("result", "blur");
  filter.append("feOffset")
      .attr("in", "blur")
      .attr("dx", 2)
      .attr("dy", 2)
      .attr("result", "offsetBlur");

  var feMerge = filter.append("feMerge");

  feMerge.append("feMergeNode")
      .attr("in", "offsetBlur")
  feMerge.append("feMergeNode")
      .attr("in", "SourceGraphic");

Then attach this filter to the svg element, such as a line or bar or whatever else tickles your fancy. . .

svg.append("path")
  .datum(data)
  .attr("class", "line")
  .attr("d", line)
  .attr("filter", "url(#dropshadow)");