Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

idiomatic way of drawing a triangle in d3

Tags:

d3.js

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?

like image 1000
dagda1 Avatar asked Sep 28 '15 20:09

dagda1


People also ask

How to draw triangle in d3?

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') .

What is the correct syntax to draw a circle in d3?

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.


2 Answers

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 size of the shape seems to be an area
  • the shape is centered at [0, 0]

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.

like image 178
Glenn Avatar answered Oct 19 '22 10:10

Glenn


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

like image 9
Kyle R Avatar answered Oct 19 '22 10:10

Kyle R