Vertical / horizontal data lines in d3

I am trying to draw a series of vertical lines on a d3 chart. The data source for this is the list of x positions (in the data), which is displayed through the scale function x() to give the correct position.

This is currently implemented as a for loop for each entry in the labels variable. The origin and endpoint y are taken from minY and maxY . A text label is attached to the end of the line.

 labels = [ { 'x':50, 'label':test' } var label = svg.append("g") .attr("class","ilabel") // Labels for (var i = 0; i < labels.length; i++) { labl = labels[i]; label.append('line') .attr('x1', x( labl.x ) ) .attr('y1', y( maxY ) ) .attr('x2', x( labl.x ) .attr('y2', y( minY ) ) .attr("class","ilabel-line"); label.append("text") .attr("transform", "translate(" + x( labl.x )+"," + y( maxY )+ ") rotate(-60)") .style("text-anchor", "start") .attr("dx", ".5em") .attr("class","ilabel-label") .text(labl.label); } 

How would I rewrite this using data, that is, pass the labels in the form of .data , and then repeat this to draw a series of parallel vertical lines.

 var label = svg.selectAll(".ilabel") .data(labels) .enter().append("g") .attr("class","ilabel") 

The bit I came across is the functions x() and y() . x() should, of course, return the x position of the string (which is constant for the given string), but how / what should the y function return in order to draw a line between two defined points ( minY and maxY ).

 line = d3.svg.line() .x(function(d) { return x(dx); }) .y(function(d) { return y(dy); }); label.append('path') .attr("d", line) 

I feel like I'm missing something obvious.

+1
data-driven
source share
2 answers

I ended up using rect regions as hatched regions, preferring lines. However, returning to this, I realized that the code is almost the same for drawing a series of rectangles compared to a number of straight lines. The confusion came from the d3 .line() function, which is used to generate a path . However, you can create a series of straight lines using svg:line and passing data through the generator function (here wrapped in a dictionary):

 var line = { 'x1':(function(d) { return x( labl.x ); }), 'y1':(function(d) { return y( maxY ); }), 'x2':(function(d) { return x( labl.x ); }), 'y2':(function(d) { return y( minY) }), } var label = svg.selectAll(".labels") .data(labels) .enter(); label.append("svg:line") .attr("x1", line.x1) .attr("y1", line.y1) .attr("x2", line.x2) .attr("y2", line.y2) .attr("class","label-line"); 
0
source share

You can simply use the axis functions in d3. Take a look at this example on Bl.ocks , you can easily set ticks using tickValues, and then tick lengths using innerTickSize and outerTicksize. You also need to set the orientation.

+3
source share

All Articles