Draw a triangle with d3 / svg

14,138 views
Skip to first unread message

Mike Heavers

unread,
Apr 4, 2012, 3:17:52 PM4/4/12
to d3...@googlegroups.com
Hi - I have successfully created a bar chart with d3, however the visual reference I have for the chart shows each bar with a triangular, pointed end. How would I create this triangle in d3?

johnrgoodall

unread,
Apr 5, 2012, 10:43:15 AM4/5/12
to d3...@googlegroups.com
To make a triangle, use the svg 'path' element (http://www.w3.org/TR/SVG11/paths.html)

svg.append('path')
      .attr('d', function(d) { 
        var x = 100, y = 100;
        return 'M ' + x +' '+ y + ' l 4 4 l -8 0 z';
      });

The tricky part will be determining where to draw it. The 'M' says move to the absolute position you specify with the x and the y (here it is 100 / 100). Lowercase 'l' says, relative to the previous command, draw a line to this point. So here we are starting at 100, 100, then drawing a line 4 to the right and 4 pixels down, then another line 8 pixels to the left. The final z says to close the path, drawing another line to the starting point. Look at the w3.org reference page for more path commands.

Is that what you were looking for?

Mike Bostock

unread,
Apr 6, 2012, 12:36:58 AM4/6/12
to d3...@googlegroups.com
> http://www.w3.org/TR/SVG11/paths.html

Yep, I'd probably use a path element with a custom "d" attribute here.

Another option for drawing triangles, but more intended for
scatterplots, is to use d3.svg.symbol. See the documentation here:

https://github.com/mbostock/d3/wiki/SVG-Shapes#wiki-symbol

Mike

Siddharth P

unread,
May 12, 2016, 3:18:18 AM5/12/16
to d3-js, mbos...@cs.stanford.edu
However I didn't find any way to point triangle side ways . Is up-down the only direction for the equilateral triangle.

Kai Chang

unread,
May 12, 2016, 11:48:25 AM5/12/16
to d3...@googlegroups.com

Try applying a rotate transform. Tutorial on transforms: https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Basic_Transformations

--
You received this message because you are subscribed to the Google Groups "d3-js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to d3-js+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages