Box plot with dual dimension and dual x-axis using dc.js - d3.js

Is it possible with dc.js to draw two x-axis of a graph i.e. one is below and one is above. One Dimension/ x-axis contain a b and above x-axis contain 1 (a b with below a-axis) 2 (a b with below x-axis). An img is attached to explain the view. If it is possible kindly give some suggestion.
Regards.

As for adding lines between the box plots, here is a hacky solution that works ok. Would probably need some work to make it general.
Assume we have the domain (['1A', '1B', '2A, '2B', ...]) in a variable called domain.
We can add a pretransition handler that draws lines after every second box:
function x_after(chart, n) {
return (chart.x()(domain[n]) + chart.x()(domain[n+1])) / 2 + chart.margins().left + 7; // why 7?
}
chart.on('pretransition', chart => {
let divide = chart.g().selectAll('line.divide').data(d3.range(domain.length/2));
divide.exit().remove();
divide = divide.enter()
.append('line')
.attr('class', 'divide')
.attr('stroke', 'black')
.merge(divide);
divide
.attr('x1', n => x_after(chart, n*2 + 1))
.attr('x2', n => x_after(chart, n*2 + 1))
.attr('y1', chart.margins().top)
.attr('y2', chart.margins().top + chart.effectiveHeight())
})
This uses the D3 general update pattern to add a vertical line after every other box (specifically those with odd index number).
It takes the average of the X position of 1B and 2A, 2B and 3A, etc. I have no idea why I had to add 7, so probably I am missing something.
demo fiddle.

Related

d3.js dynamically generated sentence map with curved text

I have the following d3.js fiddle that prints sentences in a wavy line.
As you can see it prints them all overlapping each other. How can I instead achieve the following effect aka fitting them in as best they could going from top to bottom (with some randomness and wavyness)?
The key is of course in the line:
.append("path").attr("d", "M 10,90 Q 100,15 200,70 Q 340,140 400,30");
but how can I generate these strings to do what I want?
EDIT: Sorry, just fixed wrong js fiddle link!
You can set the transform attribute to move the coordinate system of the elements you append. This way, you can offset each new element by a random amount:
svg.append("g")
.attr("transform", "translate(" + (Math.random() * 50) + "," + (i * (50 + Math.random() * 100)) + ")")
Complete demo here. You may have to tweak the numbers to get exactly what you want.

Graph ~ axis alignment issue

I'm currently working on a quite basic graph using 2 ordinal axes. X axis shows 4 categories, Y axis shows 3. For some reason, the plotted circles don't align with the plotted axes.
An example can be seen at http://jsfiddle.net/SrdY6/. Problem seems to be translation-related, but the only translation in there is applied to the large containing <g> element:
var lunchgraph = svg.append("g")
.attr("class", "lunchgraph")
.attr("transform", "translate(" + lunchmargin.left + "," + lunchmargin.top + ")");
I've been looking at this for some time now, but can't spot where things go wrong... Anyone with more insight?
Nothing like putting a question out there and risking public shame, only to find out the answer within minutes after posting.
For ordinal axes configured with rangeBands or rangeRoundBands, the scale function returns the lower value of the given input. To have the plot align with the exact categorical labels, you need to add half of the rangeBand to the calculated coordinate.
So: no problem with the translations or anything, but with the computation of cx and cy coordinates for placing the circles in the graph.
Correct code:
.attr("cx", function(d) { return x(d.label) + x.rangeBand()/2 ;} )
.attr("cy", function(d) { return y(d.sqid) + y.rangeBand()/2 ; } )

draw a grid or rectangles using a scale

I'm building my first line graph in d3:
http://jsfiddle.net/j94RZ/
I want to know how to utilize either the scale or axis allow me to draw a grid (of, presumably rectangles) where I can set a different background colour for each of the section of the grid...so I can alternate colours for each cell of the grid. I want the grid to be drawn and be constrained by the axes of my graph and then also adapt if the spacing of the axes ticks change (i.e. the axes changes like this: http://bl.ocks.org/mbostock/1667367). So if my graph has an x axis with 4 ticks and a y axis of 7 ticks then my graph will have a background grid that's 7 blocks high and 4 blocks wide.
I've been playing with the idea of using a range which starts at zero and ends at the full width of the graph but I don't know what value I can use for the step. Is there any way to sort of query the axis and return how many ticks there are?
var gridRange = d3.range(0, width, step?);
A better approach than your current solution would be to use scale.ticks() explicitly to get the tick values. The advantage of that is that it will still work if you change the number of ticks for some reason.
To get an alternating grid pattern instead of a single fill, you can use something like this code.
.attr("fill", function(d, i) {
return (i % 2) == 1 ? "green" : "blue";
})
Finally, to get the full grid pattern, you can either use an explicit loop as you've suggested, or nested selections. The idea here is to first pass in the y ticks, create a g element for each and then pass the x ticks to each one of these groups. In code, this looks something like this.
svg.selectAll("g.grid")
.data(y.ticks()).enter().append("g").attr("class", "grid")
.selectAll("rect")
.data(x.ticks()).enter().append("rect");
To set the position, you can access the indices within the top and bottom level data arrays like this.
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d, i, j) {
return yScale(j);
})
To set the x position, you need the index of the inner array (passed to the set of g elements), which can be accessed through the second argument of your callback. For the outer array, simply add another argument (j here).
And that's really all there is to it. Complete jsfiddle here. To update this grid dynamically, you would simply pass in the new tick values (gotten from scale.ticks()), match with the existing data, and handle the enter/update/exit selections in the usual manner.
If you want to do without the auxiliary scales (i.e. without .rangeBand()), you can calculate the width/height of the rectangles by taking the extent of the range of a scale and dividing it by the number of ticks minus 1. Altogether, this makes the code a bit uglier (mostly because you need one fewer rectangle than ticks and therefore need to subtract/remove), but a bit more general. A jsfiddle that takes this approach is here.
So after a few helpful comments above I've got close to a solution. Using Ordinal rangebands get me close to where I want to go.
I've created the range bands by using the number of ticks on my axis as a basis for the range of the input domain:
var xScale = d3.scale.ordinal()
.domain(d3.range(10))
.rangeRoundBands([0, width],0);
var yScale = d3.scale.ordinal()
.domain(d3.range(4))
.rangeRoundBands([0, height],0);
I've then tried drawing the rectangles out like so:
svg.selectAll("rect")
.data(p)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d,i) {
0
})
.attr("width", xScale.rangeBand())
.attr("height", yScale.rangeBand())
.attr("fill", "green").
attr('stroke','red');
This gets me the desired effect but for only one row deep:
http://jsfiddle.net/Ny2FJ/2/
I want,somehow to draw the green blocks for the whole table (and also without having to hard code the amount of ticks in the ordinal scales domain). I tried to then apply the range bands to the y axis like so (knowing that this wouldn't really work though) http://jsfiddle.net/Ny2FJ/3/
svg.selectAll("rect")
.data(p)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d,i) {
return yScale(i);
})
.attr("width", xScale.rangeBand())
.attr("height", yScale.rangeBand())
.attr("fill", "green").
attr('stroke','red');
The only way I can think to do this is to introduce a for loop to run the block of code in this fiddle http://jsfiddle.net/Ny2FJ/2/ for each tick of the y axis.

d3 transitioning from bar to pie and back

LIVE DEMO
So I have this notion that all single axis data should be allowed to be displayed in all the basic ways; and at the very least from a pie to a bar. Ideally this would be an animated transition, but thats were the difficulty comes in.
Getting a pie chart to work is easy enough, as is getting a bar chart. Here is what I have so far:
# fields
width = 750
height = width/2
margin = 20
radius = (height-(margin*2))/2
# helpers
pie = d3.layout.pie().value (d) -> d
arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius/4)
x = d3.scale.linear().domain([0, 100]).range [0, width]
$http.get('/Classification_Top_10_by_Count.json').success (data) ->
percents = (parseFloat item.Percent for item in data).sort d3.ascending
svg = d3.select('#svgStage').append('svg')
.attr('width', width+(margin*2))
.attr('height', height+(margin*2))
svg.data([percents])
g = svg.append('g')
.attr('transform', "translate(#{radius},#{radius})")
paths = g.selectAll 'path'
paths.data(pie).enter().append('path')
.attr('d', arc)
toBars = ->
g.selectAll('path').transition().duration(2000)
.attr 'd', (d, index) ->
# this is over complex because I was playing with it.
cord =
tl : [0, index*20]
tr : [d.value*20, index*20]
br : [d.value*20, index*20-20]
bl : [0, index*20-20]
oCord = [
cord.tl
cord.tr
cord.br
cord.bl
]
"M #{oCord[0][0]}, #{oCord[0][2]}
A 0, 0 0 0, 0 #{oCord[1][0]}, #{oCord[1][3]}
L #{oCord[2][0]}, #{oCord[2][4]}
A 0, 0 0 0, 0 #{oCord[3][0]}, #{oCord[3][5]}
Z"
Obviously for this to work its got to be path element to path element, and the transition is working now. Problem is it looks like crap. The moment it starts it looks garbled, until it over and becomes decent bar chart.
I've been looking at this : http://d3-example.herokuapp.com/examples/showreel/showreel.html
Which demonstrates a bar transitioning to a donut in much the way I would like. Looking at the source code, this is accomplished through a custom tween. (view source line 518)
Now I'm in over my head. What is going on here? How can I get this transition to work? Has anyone else out there dealt with this problem?
UPDATE
Just to be clear, below illustrations the intention of my transition abit more clearly.
Bounty clarity. I added a bounty to this question because I need an explanation of what was going wrong. Superboggly did that, so he got the bounty. However Amit Aviv's approach is superior, so I accept his answer as the most correct. I have also +1ed both.
Here is my take: http://jsfiddle.net/amitaviv99/x6RWs/42/
My approach was to approximate both the arcs & bars using cubic bezier curves, with the exact same number of control points. The code is somewhat complicated, and need some work. But the result is quite smooth.
Here is an excerpt (SO requires..)
var bezierArc = function(radiusIn, radiusOut, startAngle, endAngle){
var arcIn = makeCompArc(radiusIn, startAngle, endAngle);
var arcIOut = makeCompArc(radiusOut, startAngle, endAngle);
var lines = makeBezierDoubleLine(radiusIn, radiusOut, startAngle, endAngle);
var path = [arcIn, lines[0], arcOut, lines[1]].join(' ');
return path;
}
D3 does a pretty good job of interpolating between paths, but it was having trouble with your original before and after path so instead of taking over the whole tweening process myself I thought maybe we could come up with better paths to make the job easier for D3. My result.
The first thing is to look at the svg arc path element. It basically goes like this:
A rx,ry a f1,f2 x,y
you can read the details here. This will draw an arc from wherever you are (previous final coordinate) to the coordinates x,y. But the things to focus on are that the first two numbers are the implied ellipse's radii and the last part before the end coordinates, that I've marked f1,f2, are flags and so not interpolate-able.
So the main weirdness in the transition from your code is because you are trying to interpolate between
A rx,ry, 0 0,1
A 0,0 0 0,0
You will immediately see a smoother transition if you set your end-path to A0,0 0 0,1 in the one case.
To make the pieces fit together a bit better I animated the pie's inner radius so that the segments looked more like the bars but curved, then I let D3 figure out the curve-to-bar transition but without switching the arc flag. Then you want the bars to have flat ends. The path will have a flatter arc if you increase your implied ellipses radii! So I simply used 100,100. My final transition-to path for the bars looks like:
"M " + oCord[0][0] + "," + oCord[0][1] +
"A100,100 0 0,1 " + oCord[1][0] + "," + oCord[1][1] +
"L " + oCord[2][0] + "," + oCord[2][1] +
"A100,100 0 0,0 " + oCord[3][0] + "," + oCord[3][1] +
"Z";
Then To actually, properly, flatten the endpoints I have a second transition (they run serially) to zero the Arc segments of the path. I suspect there is a better way to do this kind of cleanup with D3 transitions, but a transition with duration 0 also works.
To get the reverse to work nicely I set the paths to the flattened-arc-curves from above. Having the large radius and correct flags means the D3-computed transition back to the doughnut chart works well. Then I simply animate the inner radius back out.

How to add a rectangle to specified axis in D3

I have a zoomable area plot done in D3, which works well. Now I am trying to add a rectangle to the specified location along x-axis in the middle of the plot. However, I can't seem to figure out how to do that. "rect" element is specified using absolute (x,y) of the plot and so when using zooms it stays in the same position.
So I was wondering if there is a way to tie "rect" to the axis when plotting, so that it benefits from all the zoom and translate behaviour or do I need to manually edit the x,y,width and length of the rectangle according to translation as well as figuring out where the corresponding x and y coordinates are on the graph? I am trying to use "rect" because it seems the most flexible element to use.
Thanks
Alex
I'm not sure how you are doing the zooming, but I am guessing you are changing the parameters of the scales you use with your axis? You should be able to use the same scales to place your rectangle.
If you are starting with plot coordinates then maybe using the invert function on the scale will help (available at least for quantitive scales), e.g. https://github.com/mbostock/d3/wiki/Quantitative-Scales#wiki-linear_invert
You should be able to take initial plot coordinates and invert them to determine data coordinates that can then move with changes in the scale.
If the scale is linear you can probably invert the length and width too, but you will have to compute offsets if your domain does not include 0. Easiest is to compute the rectangle's end points, something like:
var dataX0 = xScale.invert(rect.x);
var dataX1 = xScale.invert(rect.x + rect.width);
var dataWidth = dataX1 - dataX0;
If you have the data in axes coordinates already you should be able to do something like:
var rectData = [{x: 'April 1, 1999', y: 10000, width: 100, height:100}];
svg.selectAll('rect.boxy')
.data(rectData)
.enter().append('rect').classed('boxy', true)
.style('fill','black');
svg.selectAll('rect.boxy')
.attr('x', function(d) { return x(new Date(d.x));} )
.attr('y', function(d) { return y(d.y);})
.attr('width', function(d) { return d.width;} )
.attr('height', function(d) { return d.height;} );
Based on the example you shared where x and y (as functions) are the scales the axes are based on.

Resources