I have the following code that draws a triangle in d3:
var trianglePoints = xScale(3) + ' ' + yScale(18) + ', ' + xScale(1) + ' ' + yScale(0) + ', ' + xScale(12) + ' ' + yScale(3) + ' ' + xScale(12) + ', ' + yScale(3) + ' ' + xScale(3) + ' ' + yScale(18);
console.log(trianglePoints);
svg.append('polyline')
.attr('points', trianglePoints)
.style('stroke', 'blue');
Here is a jsbin which shows it in action.
I am curious to know if this is the best way of doing in this d3 or is there a better way?
I have the following code that draws a triangle in d3: var trianglePoints = xScale(3) + ' ' + yScale(18) + ', ' + xScale(1) + ' ' + yScale(0) + ', ' + xScale(12) + ' ' + yScale(3) + ' ' + xScale(12) + ', ' + yScale(3) + ' ' + xScale(3) + ' ' + yScale(18); console. log(trianglePoints); svg. append('polyline') .
var circle = d3. selectAll("circle"); With a selection, we can make various changes to selected elements. For example, we might change the fill color using selection.
Another example using v4 of shape symbols:
var color = "green";
var triangleSize = 25;
var verticalTransform = midHeight + Math.sqrt(triangleSize);
var triangle = d3.symbol()
.type(d3.symbolTriangle)
.size(triangleSize)
;
svg.append("path")
.attr("d", triangle)
.attr("stroke", color)
.attr("fill", color)
.attr("transform", function(d) { return "translate(" + xScale(currentPrice) + "," + yScale(verticalTransform) + ")"; });
;
Some notes:
The above example is trying to translate the top point of the equilateral triangle rather than the center, hence the extra amount to the "y" portion of the transfrom.
Mike Bostock, the creator of D3, thinks that what you're doing is the best method: https://groups.google.com/forum/#!topic/d3-js/kHONjIWjAA0
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With