Adding pretransition interferes with legend hover / click - dc.js

I want to modify the default transition on a multi-series chart and managed to achieve it using the "pretransition" event listener, but doing it this way seems to disable the highlighting you get "for free" with the DC legend. Assuming Michelson–Morley experiment data is loaded the usual way my code looks like this:
// MULTI-SERIES LINE CHART
const runDimension = morley.dimension(d => [d.Expt, d.Run]);
const runGroup = runDimension.group().reduceSum(d => d.Speed);
const multiSeries = new dc.SeriesChart("#multi-series");
multiSeries
.width(500)
.height(300)
.chart(cht => dc.lineChart(cht).curve(d3.curveBasis))
.dimension(runDimension)
.group(runGroup)
.keyAccessor(d => d.key[1])
.valueAccessor(d => d.value)
.seriesAccessor(d => d.key[0])
.legend(dc.legend().x(50).y(250).itemHeight(15).gap(5).horizontal(2).legendWidth(500))
.x(d3.scaleLinear().domain([1, 20]));
multiSeries.on("pretransition", function(chart) {
const path = chart.selectAll("path.line");
const totalLength = path.node().getTotalLength();
path
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(1000)
.attr("stroke-dashoffset", 0);
});
Is there a way to keep both the custom transition and the legend functionality?

Note: there are three answers below. The first is a red herring, the second is a klunky solution, and the final answer nails it! I'm preserving the false leads because they contain some useful info.
namespacing event listeners
To avoid conflicts, you can add a name as documented in D3's dispatch.on:
The type may be optionally followed by a period (.) and a name; the optional name allows multiple callbacks to be registered to receive events of the same type, such as start.foo and start.bar.
In your example:
multiSeries.on("pretransition.foo", function(chart) {
Use whatever name you want, as long as it's unique.
Internally, dc.js should do this as well, to prevent conflicts proactively.
legend matching
Digging deeper into your example, the actual source of conflict is that the legend matches with associated charts based on the color and the dashstyle. (Yes, it is weird that the legend matches items based on their attributes rather than by ID.)
I was able to get a basic example working by changing the legend items, but I think it was only because totalLength is incorrect (0).
let leg = chart.legendables;
chart.legendables = function() {
return leg.apply(chart).map(l => ({...l, dashstyle: [0,0]}));
}
It also changed the legend from squares to lines:
Fiddle.
Anyway, that's the reason it wasn't working - nothing to do with events, just the weird way the legend works. Chances are this solution won't work if totalLength and the dashstyle are correct. I didn't see the affect of your transitions, so it's likely something is wrong.
overriding the line chart
It's pretty easy to override the logic in the line chart so that it only looks at colors, not dash styles.
One way to do this is by deriving an ES6 class from it:
class LineChartNoDashMapping extends dc.LineChart {
_colorFilter (color, dashstyle, inv) {
return function () {
const item = d3.select(this);
const match = item.attr('stroke') === color || item.attr('fill') === color;
return inv ? !match : match;
};
}
}
_colorFilter is copied straight from dc.LineChart (source) and we just remove the clause having to do with dash styles. (We also have to qualify d3.select.)
Plug our new class into the series chart:
.chart(function(c) { return new LineChartNoDashMapping(c).curve(d3.curveCardinal); })
Now the legendables override isn't needed, and the legend works as expected. Much nicer!
New fiddle.

Related

Unable to reset the focus ordinal bar chart

I am trying to reset after choosing some of the individual's bar.
index.html: (line no. 62)
<span>
reset
</span>
This seems not to work. I was able to reset all the graphs pie chart, line chart, etc but not this one.
Those two ordinal graphs are created in index.js like this:
var focus = new dc.barChart('#focus');
var range = new dc.barChart('#range');
https://blockbuilder.org/ninjakx/483fd69328694c6b6125bb43b9f7f8a7
Update:
It looks weird now Coz it's showing a single bar and all the bar have got invisible but I want them to be visible (in gray colour) but not clickable.
This example replaces the built-in filtering functionality of the bar chart with its own implementation of ordinal selection, because the chart has a linear scale.
The example uses a global variable focusFilter to store the current selection. We need to empty this out and we also need to update the dimension filter as the original filterAll would do, pulling that code out of the click handler:
focus.applyFilter = function() { // non-standard method
if(focusFilter.length)
this.dimension().filterFunction(function(k) {
return focusFilter.includes(k);
});
else this.dimension().filter(null);
};
focus.filterAll = function() {
focusFilter = [];
this.applyFilter();
};
This will also allow dc.filterAll() to work, for a "reset all" link.
Fork of your block.
For some reason, I could not get the original
reset
links to work at all in this block, so I replaced them with the equivalent D3 click handlers:
d3.select('#reset-focus').on('click', () => {
focus.filterAll();
dc.redrawAll();
})
d3.select('#reset-all').on('click', () => {
dc.filterAll();
dc.redrawAll();
})
I also updated the focus ordinal bar example. Note that automatic hiding/showing of the reset link doesn't work because the chart still has an irrelevant range filter inside of it.

dc.js Line Chart doesn't show Data

Data doesn't show in my line chart. It just shows the y-axis and x-axis.
My data arrays are like this:
time_list = ['00:00:00', '01:00:00', '02:00:00']
val_list = [0.7274859768018719, 0.6894762867153069, 0.6994151884676558]
I set up the chart like this:
<div id="#chart-cpu-performance"></div>
<script type="text/javascript">
var cpuperformance = dc.lineChart("#chart-cpu-performance");
var connection = new WebSocket(`ws://localhost:8001/websocket`);
function render_plots(dim, val) {
cpuperformance
.width(990)
.height(540)
.dimension(dim)
.group(val)
.x(d3.scaleBand().domain(['00:00:00', '04:00:00', '08:00:00','12:00:00',
'16:00:00', '20:00:00','23:00:00']).rangeRound([0,100]))
.y(d3.scaleLinear().domain([0,1]))
.curve(d3.curveLinear)
.renderArea(false)
.renderDataPoints(true);
cpuperformance.render();
}
connection.onmessage = function(event){
//get data and parse
var newData = JSON.parse(event.data);
var updateObject = []
newData.time_list.forEach(function additem(item, index) {
updateObject.push({time: item, avg_value: newData.val_list[index]})
});
var xfilter = crossfilter(updateObject)
var timeDim = xfilter.dimension(function(d) {return d.time;});
var avg_vPertime = timeDim.group().reduceSum(function(d) {return +d.avg_value;});
render_plots(timeDim, avg_vPertime)
}
</script>
Did I miss some parameters for cpuperformance in the render_plots function?
Yes, you missed xUnits. Also I suggest using .elasticX(true) rather than specifying the domain yourself.
Unfortunately most coordinate grid charts are not able to determine automatically what kind of data keys they are dealing with, the primary kinds being numeric, ordinal, and time.
So if your data is ordinal, you need to have
.xUnits(dc.units.ordinal)
A lot of the logic is different for charts with an ordinal X scale, and this parameter directs dc.js to use the ordinal logic. Other values tell bar charts how wide to make the bars for the numeric (dc.units.integers, dc.units.fp.precision) and time scales (d3.timeHours etc).
Also in this example, only one of the data points matches the domain you passed to scaleBand. So you'll only see one point.
It's easier to use
.elasticX(true)
.x(d3.scaleBand().rangeRound([0,100]))
and let the chart figure out what to put in the domain.
Fiddle with a working version of your code.

dc.js - dynamically change valueAccessor of a stacked layer in a lineChart and redraw it

I am trying to realize a dashboard to display basic data.
I am actually completely stuck on an issue. Strangely enough, I couldn't find anything even similar to it online, so I don't have many leads on how to move forward.
I have mainly two charts:
a lineChart called "stackChart" that
displays consumption as a base layer with its valueAccessor function
dispalys production as a stacked layer with its value Accessor function
a barChart called "volumeChart" that is simply the rangeChart for the lineChart
I use radio buttons to select whether to aggregate the grouped data by sum or by average (using the same approach as this example) and then I just use:
stackChart.valueAccessor(/*function with new value (avg or sum)*/);
dc.redrawAll();
to refresh the base layer (consumption).
What I don't manage to do is to refresh the "stacked layer" by updating its valueAccessor! I can't find any way to access its valueAccessor (or, worst case, just completely remove the stacked layer and then add a new refreshed stacked layer using just ".stack(...)").
Here is the respective part of my code where the chart is built:
// Charts customization #js
stackChart
.renderArea(true)
.height(350)
.transitionDuration(1500)
.dimension(dateDim)
.group(powByTime, "Consumption")
// BASE LAYER valueAccessor HERE
.valueAccessor(function(d) { return d.value.conSum; })
.x(d3.time.scale().domain([minDate, maxDate]))
.xUnits(d3.time.days)
.elasticY(true)
.renderHorizontalGridLines(true)
.legend(dc.legend().x(80).y(0).itemHeight(13).gap(5))
.brushOn(false)
// STACKED LAYER HERE
.stack(powByTime, "Production", function(d) { return d.value.prodSum; })
.rangeChart(volumeChart)
.controlsUseVisibility(true)
;
And here is where I look for changes in the radio buttons and re-draw the layers:
// Listen for changes
d3.selectAll('#select-operation input')
.on('click', function() {
var aggrMode = this.value; // fetch "avg" or "sum" from buttons
// UPDATE BASE LAYER HERE:
stackChart.valueAccessor(function(d) { var sel = accessors[aggrMode]['consPow']; return d.value[sel]; });
// ???HOW TO UPDATE STACKED LAYER valueAccessor function???
//stackChart.stack.valueAccessor(function(d) { var sel = accessors[aggrMode]['prodPow']; return d.value[sel]; });
dc.redrawAll();
});
If you need more details on what I am trying to do and full code you can check here.
As a reference, here is what it looks like:
I don't really know dc.js, but it may be possible that you can't change an accessor once it's been set. Try writing a single function for your accessor that will return either the sum or the average, depending on the state of some variable that you can set.
#Ryan's solution will probably work fine (and may be a better design), but here's the lowdown on the dc.js API with respect to stacking, in case you need it.
As described in this issue the group and stack API is pretty weird. It grew organically, in a backward-compatible way, so both the stacks and the value accessors on top of the stacks sort of branch out in a beautiful fractal of... well, no it's pretty messy.
But the issue also suggests the solution for your problem. Since chart.group() resets the set of stacks, just go ahead and build them all from scratch in your event handler:
stackChart.group(powByTime, "Consumption") // this resets the stacks
.valueAccessor(function(d) { var sel = accessors[aggrMode]['consPow']; return d.value[sel]; })
.stack(powByTime, "Production", function(d) { var sel = accessors[aggrMode]['prodPow']; return d.value[sel]; });
Internally it's just emptying an array of layers/stacks and then populating it with some references.
This is quite efficient since dc.js doesn't store your data except where it is bound to the DOM elements. So it is the same amount of work to redraw using the old group and value accessor as it is to redraw using new ones.

D3JS Circle on top of each other [duplicate]

What is an effective way to bring an SVG element to the top of the z-order, using the D3 library?
My specific scenario is a pie chart which highlights (by adding a stroke to the path) when the mouse is over a given piece. The code block for generating my chart is below:
svg.selectAll("path")
.data(d)
.enter().append("path")
.attr("d", arc)
.attr("class", "arc")
.attr("fill", function(d) { return color(d.name); })
.attr("stroke", "#fff")
.attr("stroke-width", 0)
.on("mouseover", function(d) {
d3.select(this)
.attr("stroke-width", 2)
.classed("top", true);
//.style("z-index", 1);
})
.on("mouseout", function(d) {
d3.select(this)
.attr("stroke-width", 0)
.classed("top", false);
//.style("z-index", -1);
});
I've tried a few options, but no luck so far. Using style("z-index") and calling classed both did not work.
The "top" class is defined as follows in my CSS:
.top {
fill: red;
z-index: 100;
}
The fill statement is there to make sure I knew it was turning on/off correctly. It is.
I've heard using sort is an option, but I'm unclear on how it would be implemented for bringing the "selected" element to the top.
UPDATE:
I fixed my particular situation with the following code, which adds a new arc to the SVG on the mouseover event to show a highlight.
svg.selectAll("path")
.data(d)
.enter().append("path")
.attr("d", arc)
.attr("class", "arc")
.style("fill", function(d) { return color(d.name); })
.style("stroke", "#fff")
.style("stroke-width", 0)
.on("mouseover", function(d) {
svg.append("path")
.attr("d", d3.select(this).attr("d"))
.attr("id", "arcSelection")
.style("fill", "none")
.style("stroke", "#fff")
.style("stroke-width", 2);
})
.on("mouseout", function(d) {
d3.select("#arcSelection").remove();
});
As explained in the other answers, SVG does not have a notion of a z-index. Instead, the order of elements in the document determines the order in the drawing.
Apart from reordering the elements manually, there is another way for certain situations:
Working with D3 you often have certain types of elements that should always be drawn on top of other types of elements.
For example, when laying out graphs, links should always be placed below nodes. More generally, some background elements usually need to be placed below everything else, while some highlights and overlays should be placed above.
If you have this kind of situation, I found that creating parent group elements for those groups of elements is the best way to go. In SVG, you can use the g element for that. For example, if you have links that should be always placed below nodes, do the following:
svg.append("g").attr("id", "links")
svg.append("g").attr("id", "nodes")
Now, when you paint your links and nodes, select as follows (the selectors starting with # reference the element id):
svg.select("#links").selectAll(".link")
// add data, attach elements and so on
svg.select("#nodes").selectAll(".node")
// add data, attach elements and so on
Now, all links will always be appended structurally before all node elements. Thus, the SVG will show all links below all nodes, no matter how often and in what order you add or remove elements. Of course, all elements of the same type (i.e. within the same container) will still be subject to the order in which they were added.
One of the solutions presented by the developer is: "use D3's sort operator to reorder the elements." (see https://github.com/mbostock/d3/issues/252)
In this light, one might sort the elements by comparing their data, or positions if they were dataless elements:
.on("mouseover", function(d) {
svg.selectAll("path").sort(function (a, b) { // select the parent and sort the path's
if (a.id != d.id) return -1; // a is not the hovered element, send "a" to the back
else return 1; // a is the hovered element, bring "a" to the front
});
})
Since SVG doesn't have Z-index but use the order of the DOM elements, you can bring it to front by:
this.parentNode.appendChild(this);
You can then e.g. make use of insertBefore to put it back on mouseout. This however requires you to be able to target the sibling-node your element should be inserted before.
DEMO: Take a look at this JSFiddle
The simple answer is to use d3 ordering methods. In addition to d3.select('g').order(), there is .lower() and .raise() in version 4. This changes how your elements appear. Please consult the docs for more information - https://github.com/d3/d3/blob/master/API.md#selections-d3-selection
SVG doesn't do z-index. Z-order is dictated by the order of the SVG DOM elements in their container.
As far as I could tell (and I've tried this a couple of times in the past), D3 doesn't provide methods for detaching and reattaching a single element in order to bring it to the front or whatnot.
There is an .order() method, which reshuffles the nodes to match the order they appear in the selection. In your case, you need to bring a single element to the front. So, technically, you could resort the selection with the desired element in front (or at the end, can't remember which is topmost), and then call order() on it.
Or, you could skip d3 for this task and use plain JS (or jQuery) to re-insert that single DOM element.
I implemented futurend's solution in my code and it worked, but with the large number of elements I was using, it was very slow. Here's the alternative method using jQuery that worked faster for my particular visualization. It relies on the svgs you want on top having a class in common (in my example the class is noted in my data set as d.key). In my code there is a <g> with the class "locations" that contains all of the SVGs I'm re-organizing.
.on("mouseover", function(d) {
var pts = $("." + d.key).detach();
$(".locations").append(pts);
});
So when you hover on a particular data point, the code finds all the other data points with SVG DOM elements with that particular class. Then it detaches and re-inserts the SVG DOM elements associated with those data points.
Wanted to expand on what #notan3xit answered rather than write out an entire new answer (but I don't have enough reputation).
Another way to solve the element order problem is to use 'insert' rather than 'append' when drawing . That way the paths will always be placed together before the other svg elements(this assumes your code already does the enter() for links before the enter() for the other svg elements).
d3 insert api: https://github.com/mbostock/d3/wiki/Selections#insert
It took me ages to find how to tweak the Z-order in an existing SVG. I really needed it in the context of d3.brush with tooltip behavior. In order to have the two features work nicely together (http://wrobstory.github.io/2013/11/D3-brush-and-tooltip.html), you need the d3.brush to be the first in Z-order (1st to be drawn on the canvas, then covered by the rest of the SVG elements) and it will capture all mouse events, no matter what is on top of it (with higher Z indices).
Most forum comments say that you should add the d3.brush first in your code, then your SVG "drawing" code. But for me it was not possible as I loaded an external SVG file. You can easily add the brush at any time and alter the Z-order later on with:
d3.select("svg").insert("g", ":first-child");
In the context of a d3.brush setup it will look like:
brush = d3.svg.brush()
.x(d3.scale.identity().domain([1, width-1]))
.y(d3.scale.identity().domain([1, height-1]))
.clamp([true,true])
.on("brush", function() {
var extent = d3.event.target.extent();
...
});
d3.select("svg").insert("g", ":first-child");
.attr("class", "brush")
.call(brush);
d3.js insert() function API: https://github.com/mbostock/d3/wiki/Selections#insert
Hope this helps!
You can Do like this On Mouse Over You can Pull it to top.
d3.selection.prototype.bringElementAsTopLayer = function() {
return this.each(function(){
this.parentNode.appendChild(this);
});
};
d3.selection.prototype.pushElementAsBackLayer = function() {
return this.each(function() {
var firstChild = this.parentNode.firstChild;
if (firstChild) {
this.parentNode.insertBefore(this, firstChild);
}
});
};
nodes.on("mouseover",function(){
d3.select(this).bringElementAsTopLayer();
});
If You want To Push To Back
nodes.on("mouseout",function(){
d3.select(this).pushElementAsBackLayer();
});
Version 1
In theory, the following should work fine.
The CSS code :
path:hover {
stroke: #fff;
stroke-width : 2;
}
This CSS code will add a stroke to the selected path.
The JS code :
svg.selectAll("path").on("mouseover", function(d) {
this.parentNode.appendChild(this);
});
This JS code first removes the path from the DOM tree and then adds it as the last child of its parent. This makes sure the path is drawn on top of all other children of the same parent.
In practice, this code works fine in Chrome but breaks in some other browsers. I tried it in Firefox 20 on my Linux Mint machine and couldn't get it to work. Somehow, Firefox fails to trigger the :hover styles and I haven't found a way to fix this.
Version 2
So I came up with an alternative. It may be a bit 'dirty', but at least it works and it doesn't require looping over all elements (as some of the other answers).
The CSS code :
path.hover {
stroke: #fff;
stroke-width : 2;
}
Instead of using the :hover pseudoselector, I use a .hover class
The JS code :
svg.selectAll(".path")
.on("mouseover", function(d) {
d3.select(this).classed('hover', true);
this.parentNode.appendChild(this);
})
.on("mouseout", function(d) {
d3.select(this).classed('hover', false);
})
On mouseover, I add the .hover class to my path. On mouseout, I remove it.
As in the first case, the code also removes the path from the DOM tree and then adds it as the last child of its parent.
I solved it by using the raise function.
const raise = (d) => {
d3.select(d).raise()
}
And in the component that you need to raise on hover (along with all its children, just place this.
.on("mouseover", (d) => raise(d.srcElement.parentNode))
Depending on your structure, maybe parentNode is not needed. In this example they used "this" but that didn't work in React. https://codepen.io/_cselig/pen/KKgOppo

How to remove NVD3 chart resize/update delay

I've created an NVD3 multiBarChart and placed it in a jQuery resizable container. When resizing the chart, each render incurs the same delay as when the chart is first drawn: staggered left-to-right delayed drawing of the bars. This looks cool when the chart is first drawn, but it's a nuisance when resizing the chart. I've experimented with nv.d3.css, reducing every delay to 0ms to no avail. Haven't yet inspected the NVD3 JS and am hoping not to need to.
Fiddle:
http://jsfiddle.net/a5Fnj/10/
var container = $("#mycontainer");
$(container[0]).resizable();
var svg = d3.select(container[0]).append("svg");
nv.addGraph(function () {
var chart = nv.models.multiBarChart();
chart.xAxis.tickFormat(d3.format(',f'));
chart.yAxis.tickFormat(d3.format(',.1f'));
d3.select(container[0]).select("svg")
.datum(exampleData())
.transition().duration(0).call(chart);
nv.utils.windowResize(chart.update);
this.stackedbar = chart;
});
function exampleData() {
return stream_layers(3, 10 + Math.random() * 100, .1).map(function (data, i) {
return {
key: 'Stream' + i,
values: data
};
});
}
As of NVD3 1.7.1 you can use the duration option:
chart.duration(0);
I used transitionDuration: -1 that worked for a stackedAreaChart.
Edit
This helped remove the transition when appending chart data, not the re-size issue, please check the comments below.
In the latest version (from github), you can set .transitionDuration():
chart.transitionDuration(0);
Edit: Even with this, some of the transitions/durations are hardcoded in the NVD3 source. The only way to get rid of those is to modify the source.

Resources