Skip to content

Instantly share code, notes, and snippets.

@rmarimon
Created August 29, 2011 15:47

Revisions

  1. rmarimon revised this gist Aug 29, 2011. 2 changed files with 77 additions and 0 deletions.
    77 changes: 77 additions & 0 deletions index.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,77 @@
    <!DOCTYPE html>
    <html>
    <head>
    <title>Pie Chart</title>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.js"></script>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.layout.js"></script>
    <style type="text/css">

    body {
    font: 10px sans-serif;
    }

    </style>
    </head>
    <body>
    <script type="text/javascript">

    var w = 400,
    h = 400,
    r = Math.min(w, h) / 2,
    data = d3.range(10).map(Math.random),
    color = d3.scale.category20(),
    donut = d3.layout.pie().sort(d3.descending),
    arc = d3.svg.arc().innerRadius(r * .6).outerRadius(r);

    var vis = d3.select("body")
    .append("svg:svg")
    .data([data])
    .attr("width", w)
    .attr("height", h);


    // create the patterns

    var defs = vis.append('svg:defs');

    var allpatterns = defs.selectAll("pattern")
    .data(color.range())
    .enter().append('svg:pattern')
    .attr('id', function(d, i) { return "pattern-" + i; })
    .attr('width', 16)
    .attr('height', 16)
    .attr('patternUnits', 'userSpaceOnUse');

    allpatterns
    .append('svg:rect')
    .attr('width', 16)
    .attr('height', 16)
    .attr('fill', function(d, i) { return color(i); });
    allpatterns
    .append('svg:image')
    .attr('width', 16)
    .attr('height', 16)
    .attr('xlink:href', 'somepattern.gif');

    // same as Mike's example

    var arcs = vis.selectAll("g.arc")
    .data(donut)
    .enter().append("svg:g")
    .attr("class", "arc")
    .attr("transform", "translate(" + r + "," + r + ")");

    arcs.append("svg:path")
    .attr("fill", function(d, i) { return "url(#pattern-" + i + ")"; })
    .attr("d", arc);

    arcs.append("svg:text")
    .attr("transform", function(d) { return "translate(" + arc.centroid(d) + ")"; })
    .attr("dy", ".35em")
    .attr("text-anchor", "middle")
    .attr("display", function(d) { return d.value > .15 ? null : "none"; })
    .text(function(d, i) { return d.value.toFixed(2); });

    </script>
    </body>
    </html>
    Binary file added somepattern.gif
    Loading
    Sorry, something went wrong. Reload?
    Sorry, we cannot display this file.
    Sorry, this file is invalid so it cannot be displayed.
  2. rmarimon created this gist Aug 29, 2011.
    1 change: 1 addition & 0 deletions README
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    SVG Patterns Example