D3 Redraw Brush - d3.js

I have a problem that I haven't been able to solve for a number of weeks. I'm working on a modified version of this example: http://bl.ocks.org/mbostock/1667367 I've defined the brush initially so it has a brush extent between 0.5 and 0.8.
var brush = d3.svg.brush()
.x(x2)
.extent([0.5, 0.8])
.on("brush", brushed);
The brush selection shows up (on the context graph) in the correct location, but the initial view of the focus area is still set to the extent of the entire data set (and not to the clipping area of the brush). I've read that defining the brush doesn't automatically force a redraw of the area, but I can't seem to figure out how to make the view of the focus area automatically scale to the brush extents. Can someone please provide some input on this?
Update 1
I currently have a function called Brushed which does the following:
function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select("path").attr("d", Light_area);
focus.select(".x.axis").call(xAxis);
Light_line_overlay.select("path").attr("d", Light_area);
rules.select(".y.grid").call(make_x_axis_light()
.tickSize(-height, 0, 0)
.tickFormat("")
);
var xx0=brush.x()(brush.extent()[0]);
var xx1=brush.x()(brush.extent()[1]);
brushfill.attr("x", xx0);
brushfill.attr("width", xx1-xx0);
}
It's slightly different from the example... because I've been modifying it to do different things from the base example. However, the first comment suggests that I should just call this brushed function after declaring the brush (see first post). However, calling this function doesn't do anything (or at least, it doesn't update the focus area to the extents of the brush). Do you have any suggestions?

I apologize for answering this two years late but I just ran in to the same situation and this was the only resource I found on the topic. I was able to figure it out, so hopefully this will help anybody else who stumbles upon it.
The code in the original question was almost all the way there, it just didn't have the right scaling on the extent initialization.
The data I'm using is an array of objects with a ts key (which is epoch milliseconds) that I use for my x values.
// These are needed for the brush construction to know how to scale
x2.domain(x.domain());
y2.domain(y.domain());
// Pick out the ~50% and ~80% marks from the data
var N = data.length;
var cx0 = new Date(data[Math.floor(N*0.50)].ts);
var cx1 = new Date(data[Math.floor(N*0.80)].ts);
// Construct with that extent, which will leave the
// context box started in the correct position.
var brush = d3.svg.brush()
.x(x2)
.extent([cx0, cx1])
.on("brush", brushed)
;
// This is just the original brushed example
function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select(".area").attr("d", line);
focus.select(".x.axis").call(xAxis);
}
...
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")")
;
// Now that focus is defined we can manually update it
brushed();
I actually kept the call to brushed at the very end of the setup, just to keep things pretty, but the point here was just to illustrate that once focus is defined you can call brushed to do whatever updates you want there.
Ultimately it seems your main issue was getting the right type for the extent. Using [0.5, 0.8] worked on initialization, but if you check whenever brushed is called from actually sliding the focus around with the mouse, brush.extent() will be [Date(), Date()]. And that makes sense, since we're passing that extent to x.domain. So this sets up all the scaling before initializing the brush, so that the initialization extent can be a Date, then everything else is gravy.

You need to perform actions similar to the ones of the brushed function whenever your brush extent is changed programmatically. Resize the x.domain, refresh the view.
function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
}
If that doesn't solve your problem, consider providing some code example.

Related

Rendering in the background of a dc.js chart with renderlet

I use dc.js for showing the results of multiple classification algorithms. More specifically, I want to show a precision recall chart (each point corresponds to a result of a classification system).
I already used a dc.js scatter chart for this which works fine.
Additionally I would like to have a d3 contour in the background of the chart which shows the F-measure.
This is already implemented. The only issue is that the contour part is in the foreground and not in the background of the chart.
Please have a look at the jsfiddle for a full example.
Two questions are still open for me because I'm not a dc.js or d3 expert:
Is there a way to put the contour in the background or the symbols(cycles) of the scatter chart in the foreground (I already tried it with the help of this stackoverflow question but with no success)
I used the 'g.brush' selector to get the area of the inner chart. This works fine as long as the brushing is turned on. Is the selector a good way to go or are there better alternatives (which may also work if brushing is switched off).
In my example I put the contour part in the upper left corner to see if it works but I also provide the code (currently uncommented) to increase the width and height of the contour to the correct size.
chart
.on('renderlet', function (chart) {
var innerChart = chart.select('g.brush');
var width = 300, height=300;
//getting the correct width, height
//var innerChartBoundingRect = innerChart.node().getBoundingClientRect();
//var width = innerChartBoundingRect.width, height=innerChartBoundingRect.height;
[contours, color] = generateFmeasureContours(width,height, 1);
innerChart
.selectAll("path")
.data(contours)
.enter()
.append("path")
.attr("d", d3.geoPath())
.attr("fill", d => color(d.value));
var symbols = chart.chartBodyG().selectAll('path.symbol');
symbols.moveToFront();
});
jsfiddle
Putting something in the background is a general purpose SVG skill.
SVG renders everything in the order it is declared, from back to front, so the key is to put your content syntactically before everything else in the chart.
I recommend encapsulating it in an svg <g> element, and to get the order right you can use d3-selection's insert method and the :first-child CSS selector instead of append:
.on('pretransition', function (chart) {
// add contour layer to back (beginning of svg) only if it doesn't exist
var contourLayer = chart.g().selectAll('g.contour-layer').data([0]);
contourLayer = contourLayer
.enter().insert('g', ':first-child')
.attr('class', 'contour-layer')
.attr('transform', 'translate(' + [chart.margins().left,chart.margins().top].join(',') + ')')
.merge(contourLayer);
A few more points on this implementation:
use dc's pretransition event because it happens immediately after rendering and redrawing (whereas renderlet waits for transitions to complete)
the pattern .data([0]).enter() adds the element only if it doesn't exist. (It binds a 1-element array; it doesn't matter what that element is.) This matters because the event handler will get called on every redraw and we don't want to keep adding layers.
we give our layer the distinct class name contour-layer so that we can identify it, and so the add-once pattern works
contourLayer = contourLayer.enter().insert(...)...merge(contourLayer) is another common D3 pattern to insert stuff and merge it back into the selection so that we treat insertion and modification the same later on. This would probably be simpler with the newer selection.join method but tbh I haven't tried that yet.
(I think there may also have been some improvements in ordering that might be easier than insert, but again, I'm going with what I know works.)
finally, we fetch the upper-left offset from the margin mixin
Next, we can retrieve the width and height of the actual chart body using
(sigh, undocumented) methods from dc.marginMixin:
var width = chart.effectiveWidth(), height = chart.effectiveHeight();
And we don't need to move dots to front or any of that; the rest of your code is as before except we use this new layer instead of drawing to the brushing layer:
contourLayer
.selectAll("path")
.data(contours)
.enter()
.append("path")
.attr("d", d3.geoPath())
.attr("fill", d => color(d.value));
Fork of your fiddle.
Again, if you'd like to collaborate on getting a contour example into dc.js, that would be awesome!

Focus/Context Brushing + Pan/Zoom graph - How to limit panning

I've managed to make a d3.js line+area graph sync with focus/context brushing and pan/zoom, with a small example here:
http://jsfiddle.net/MtXvx/8/
I'm having trouble limiting the panning to stop at the original domain boundaries, while also working nicely with the brush. This is to prevent users from losing the graph in their view.
While I have tried manually detecting when panning has exceeded boundaries and then setting zoom.translate([0,0]), such as in these examples:
d3.js scatter plot - zoom/drag boundaries, zoom buttons, reset zoom, calculate median
Limiting domain when zooming or panning in D3.js
d3.js scatter plot - zoom/drag boundaries, zoom buttons, reset zoom, calculate median
...as I do here at line 183:
//If exceed original domain, limit panning by resetting translate
if (x.domain()[0] < x0.domain()[0]) {
zoom.translate([0, 0]);
}
The problem occurs when:
1) Create a brush region in the small context graph
2) Pan the big focus graph all the way towards the earliest date
3) Graph jumps when panning is almost at the boundary
Would appreciate any help to prevent the jumping from happening, or if there is any other way to limit the panning (and eventually the zooming out too) to the original domain boundaries.
Regarding limiting the zoom-out, setting:
var zoom = d3.behavior.zoom().x(x).scaleExtent([1,10]).on("zoom", zoomed);
...does not work nicely because the zoom-out would be limited to the brush region instead of the full extent of the graph data.
Much thanks!
I had similar problems combining D3 Brushing and Zoom & Pan, but figured it out eventually. I found the key to limit the panning is to reset the translate of the zoom behavior object. Specifically, here is my zoom callback function:
function zoomed() {
var t = d3.event.translate;
var s = d3.event.scale;
var size = width*s;
t[0] = Math.min(t[0], 0);
t[0] = Math.max(t[0], width-size);
zoom.translate(t);
focus.select(".area").attr("d", area);
focus.select(".x.axis").call(xAxis);
var brushExtent = [x.invert(0), x.invert(width)];
context.select(".brush").call(brush.extent(brushExtent));
}
While not part of your question, also an important part to make the whole demo work right is to update the zoom translate and scale when brushing is done, so here is my brushed callback:
function brushed() {
x.domain(brush.empty() ? x2.domain() : brush.extent());
focus.select(".area").attr("d", area);
focus.select(".x.axis").call(xAxis);
var s = x.domain();
var s_orig = x2.domain();
var newS = (s_orig[1]-s_orig[0])/(s[1]-s[0]);
var t = (s[0]-s_orig[0])/(s_orig[1]-s_orig[0]);
var trans = width*newS*t;
zoom.scale(newS);
zoom.translate([-trans,0]);
}
Here is a complete example based one of D3 examples: http://bl.ocks.org/sbreslav/be9af0d809b49864b7d8
to limit the extent of the panning on the graph you could use clamp, although I couldn't see where or if you were using a scale in that fiddle (actually it didn't appear to be working). Here's a simple example in a fiddle

d3 - Axis Label Transition

In Mike Bostock's cubism demo (http://bost.ocks.org/mike/cubism/intro/demo-stocks.html), there is a cursor which displays the values of all horizon charts on display. Furthermore, the cursor text shows the time axis point in time. As the cursor text obscures an axis label, the label fades.
I am working on a similar display with d3.js (but not cubism). I have all working except that fade portion. I have searched through the CSS in the developer's window, searched the source code (as best I could), but I don't understand what manner of magic is being used to accomplish this feat. I've even looked through SO "axis label transition" questions, but I have failed to connect the dots on xaxis label transitions.
How does that fade in/out when obscured by text happen?
UPDATE:
I think I located the event script area where this happens - its just a little over my head at the moment - can anyone help me decipher what this event listener is doing? Specifically, in the second g.selectAll in the else clause below - what data (d) is being used here? What is causing this event to fire?
This is the coolest part of the display (outside of the horizon charts), I would love to figure this out ...
context.on("focus.axis-" + id, function(i) {
if (tick) {
if (i == null) {
tick.style("display", "none");
g.selectAll("text").style("fill-opacity", null);
} else {
tick.style("display", null).attr("x", i).text(format(scale.invert(i)));
var dx = tick.node().getComputedTextLength() + 6;
g.selectAll("text").style("fill-opacity", function(d) { return Math.abs(scale(d) - i) < dx ? 0 : 1; });
}
}
});
I used this as reference to accomplish the same effect.
I'm not sure what the context variable is or how the id's are set or what the tick flag references but what I did was simply update the opacity of the ticks according to their proximity to the mouse. With this, the vertical tick fades as well as the label text.
svg.selectAll('.x.axis .tick').style('opacity', function (d) {
return Math.min(1, (Math.round(Math.abs(d3.mouse(svg.node())[0] - x(d))) - 10) / 15.0);
});
This way, the opacity is set to 0 if it's within 10 pixels, and fades from 1-0 between 10 and 25. Above 25, the opacity would be set to an increasingly large number, so I clamp it to 1.0 using the Math.min function.
My labels are slightly rotated, so I also added an offset not shown inside the formula above (a +3 after [0]) just to make it look a bit nicer. A year late to answer your only question, but hey it's a nice effect.
same answer as Kevin Branigan's post, but using the d3 scale to calculate the opacity value.
var tickFadeScale = d3.scale.linear().domain([10,15]).range([0,1]).clamp(true);
svg.selectAll('.x.axis .tick').style('opacity', function (d) {
return tickFadeScale(Math.abs(d3.mouse(svg.node())[0] - x(d)));
}

Update the y-axis of a brushed area chart

I am using d3.js, and I'm working on a brushed area chart by modifying this example. In addition to the x-axis changing based on the brush, I'd like chart's y-axis to be redrawn, based on the y-values of the data that fall within the brush (similar to the behavior of a Google Finance chart).
I have gotten the functionality working, but only in a way that enables the brush to be drawn in both x- and y-space. I did this by first adding a y scale to the brush variable:
var brush = d3.svg.brush()
.x(x2)
.y(y2)
.on("brush", brush);
This makes brush.extent() return the following multi-dimensional array: [ [x0, y0], [x1, y1] ]. I then use this data in the brush() function to redefine the x- and y- domain for the focus chart:
function brush() {
var extent = brush.extent();
x.domain(brush.empty() ? x2.domain() : [ extent[0][0], extent[1][0] ]);
y.domain(brush.empty() ? y2.domain() : [ extent[0][1], extent[1][1] ]);
focus.select("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
focus.select(".y.axis").call(yAxis);
}
This works, but by defining the y scale in the brush variable, the user can now drag 'boxes' in the focus chart, rather than only being able to drag west to east, as in the original chart.
Essentially, my question is: how do I get the range of values that fall within a brush's area, rather than the range of the brush's area itself? Is this even possible?
d3's brush documentation is here.
I came up with a solution.
I used the brush-filtered x.domain to filter down my original data set. This new filtered data set has only the values that fall within the brush:
// Use x.domain to filter the data, then find the max and min duration of this new set, then set y.domain to that
x.domain(brush.empty() ? x2.domain() : brush.extent());
var dataFiltered = data.filter(function(d, i) {
if ( (d.date >= x.domain()[0]) && (d.date <= x.domain()[1]) ) {
return d.duration;
}
})
y.domain([0, d3.max(dataFiltered.map(function(d) { return d.duration; }))]);
Finally, be sure to redraw the y-axis as well as the x-axis:
focus.select("path").attr("d", area);
focus.select(".x.axis").call(xAxis);
focus.select(".y.axis").call(yAxis);
A shorter possibility would be to use d3.scale.invert() on your brush.extent() like so:
var domainExtent = brush.extent().map(function(d){return scale.invert(d);});
var filteredData = data.filter(function(d){return ((d <= domainExtent[1]) && (d >= domainExtent[0]));});
However, by now d3 has gained d3.brushX(), which only allows brushing in East/West direction by design.

how to animate and play over time in d3.js?

I am a novice while working on d3.js.
I wanted to know how can we Animate some data (eg. Change colors) with respect to time.
eg. Let's say, in Monitoring app, I am projecting cluster data over US Map. Projection is done by drawing a circle and filling it by RED, GREEN or YELLOW color depending on it's status.
When we start monitoring, ideally all circles will be filled with "GREEN" color and then over time color can change to "YELLOW" or "RED" depending on how cluster is behaving.
So if I need to play these color changes over time in some time window, how can it be done ?
If you can point me to any of the similar examples , that will help too ?
Thanks
Take a look at http://mbostock.github.com/d3/tutorial/bar-2.html. Basically you'll need a redraw function that you'll call whenever you want to update your chart. (Note: there is nothing special about the name of this function, you can call it whatever you want.)
You can use setInterval to create a basic timer, this is the rate that your chart will be updated.
setInterval(function() {
redraw(); // call the function you created to update the chart
}, 1500);
Then you define redraw to update the chart data. This is a redraw function for a bar chart, but yours would be similar. You would just be adjusting the color based on the data instead of the y position and height.
function redraw() {
// Update…
chart.selectAll("rect")
.data(data)
.transition()
.duration(1000)
.attr("y", function(d) { return h - y(d.value) - .5; })
.attr("height", function(d) { return y(d.value); });
}
Note that this is a simplified version, I recommend reading the page that I linked above for a more complete example.

Resources