Disable brush resize (DC.js, D3.js) - d3.js

Brush extent needs to be changed only from a dropdown as shown here: https://jsfiddle.net/dani2011/67jopfj8/3/
Need to disable brush extending by:
1) Extending an existing brush using the handles/resize-area of the brush
Gray circles are the handels:
2) Dragging a new brush by clicking on the brush background, where the
haircross cursor appears.
JavaScript file
Removed the handles of the brush:
timeSlider.on('preRedraw',function (chart)
{
var timesliderSVG = d3.select("#bitrate-timeSlider-chart").selectAll("g.brush").selectAll("g.resize").selectAll("*").data(data[0]).exit().remove();})
If using css instead:
#bitrate-timeSlider-chart g.resize {
display:none;
visibility:hidden;
Now it looks like this:
.
The rect and the path elements inside "resize e","resize w" were removed:
However,the "resize e", "resize w" for extanding the brush still exist:
g.resize.e and g.resize.w dimesions are 0*0:
Furthurmore,after deleting "resize e","resize w" in the "developer tools/elements" in chrome,they reappear after moving the brush.
Tried to remove the resize-area in brushstart,brush,brushend:
timeSlider.on('renderlet', function (chart) {
var brushg = d3.select("#bitrate-timeSlider-chart").selectAll("g.brush");
var resizeg = brushg.selectAll("g.resize").selectAll("*").data(data[0]);
var timesliderSVG4 =
brushg.on("brushstart", function () {resizeg.exit().remove()}).on("brush", function () { resizeg.exit().remove() }).on("brushend", function () {resizeg.exit().remove() })
dc.js file
Tried to change setHandlePaths,resizeHandlePath:
1)
Remarked the _chart.setHandlePaths(gBrush):
_chart.renderBrush = function (g) {....
// _chart.setHandlePaths(gBrush);
...}
2) Changed _chart.setHandlePaths = function (gBrush) for example by removing the gbrush.path:
// gBrush.selectAll('.resize path').exit().remove();
3) Remarked/changed _chart.resizeHandlePath = function (d) {...}.
d3.js file
1) Remarked/changed resize such as:
mode: "move" //mode: "resize" ,
var resize = g.selectAll(".resize").data(resizes[0], d3_identity);
Using resizes[0] disable the brush rendering on the background but still can re-extend the existing brush
2) Remarked/changed d3_svg_brushResizes
3) In d3.svg.brush = function():
a) Added .style("display","none"):
background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("display", "none").style("cursor", "none");
b) background.exit().remove();
The cursor now is "pointer" instead of "haircross" extending the brush to a full width
c) d3_svg_brushCursor disabled makes the whole brush disappear
4) Changed the pointer-events as specified here: https://developer.mozilla.org/en/docs/Web/CSS/pointer-events
5) console.log in different places to track the different brush events:
function d3_event_dragSuppress(node) {
console.log("here2 ");
}
if (d3_event_dragSelect) {
console.log("here3 d3_event_dragSelect");
...
}
return function (suppressClick) {
console.log("suppressClick1");
...
var off = function () {
console.log("suppressClick2");
...
w.on(click, function () {
console.log("suppressClick3")
...
function d3_mousePoint(container, e) {
console.log("d3_mousePoint1")
...
if (svg.createSVGPoint) {
console.log("createSVGPoint");
...
if (window.scrollX || window.scrollY) {
console.log("createSVGPoint1");
svg = d3.select("body").append("svg").style({
...
function dragstart(id, position, subject, move, end) {
console.log("dragstart")
...
function moved() {
console.log("moved ");
console.log("transition1");
...
if (d3.event.changedTouches) {
console.log("brushstart1");
...
} else {
console.log("brushstart2");
..
if (dragging) {
console.log("dragging4");
....
if (d3.event.keyCode == 32) {
if (!dragging) {
console.log("notdragging1");
...
function brushmove() {
console.log("brushmove");
...
if (!dragging) {
console.log("brushmove!dragging");
if (d3.event.altKey) {
console.log("brushmove!dragging1");
...
if (resizingX && move1(point, x, 0)) {
console.log("resizeXMove1");
...
if (resizingY && move1(point, y, 1)) {
console.log("resizeYMove1");
...
if (moved) {
console.log("moved");
...
}
function move1(point, scale, i) {
if (dragging) {
console.log("dragging1");
...
if (dragging) {
console.log("dragging2");
...
} else {
console.log("dragging10");
...
if (extent[0] != min || extent[1] != max) {
console.log("dragging11");
if (i) console.log("dragging12"); yExtentDomain = null;
console.log("dragging13");
function brushend() {
console.log("brushend");
...
The two changes that seemed to get closest to the needed result are in d3.js:
1) Using resizes[0] disables the brush rendering on the background but still can re-extend the existing brush
var resize = g.selectAll(".resize").data(resizes[0], d3_identity);
2) Removing the brush's background changes the cursor to "pointer" instead of "haircross",extending the brush to a full width only when clicking on the graph
`background.exit().remove();`
Any help would be very appreciated!

This is from the accepted answer in Disable d3 brush resize, as suggested by #altocumulus. I didn't see a response from #Dani on this idea in particular, but thought I'd go ahead and try it, since I've seen other people try it in the past. (Probably on the dc.js users group.)
It looks a little twitchy, because d3.js will draw the brush at the new extent, and then a moment later we reset the extent to what we want, but functionally it seems to do what we want.
In dc.js the function that handles brush "rounding" is coordinateGridMixin.extendBrush:
_chart.extendBrush = function () {
var extent = _brush.extent();
if (_chart.round()) {
extent[0] = extent.map(_chart.round())[0];
extent[1] = extent.map(_chart.round())[1];
_g.select('.brush')
.call(_brush.extent(extent));
}
return extent;
};
Notice that it's following the same pattern as Lars' answer. Well, this is sort of like rounding, right? Let's override it.
First, let's store the current number of hours when it's set through the dropdown:
var graphSpan;
function addHours(amountHours) {
graphSpan = amountHours;
// ...
Next let's override coordinateGridMixin.extendBrush:
timeSlider.extendBrush = function() {
var extent = timeSlider.brush().extent();
if(graphSpan) {
extent[1] = moment(extent[0]).add(graphSpan, 'hours');
}
return extent;
}
We just replace the function. If we needed to reuse the old implementation in our function, we could use dc.override.
If graphSpan has been set, we add that amount to the beginning to get the end. If it's not set, we allow the user to specify the brush width - you'd need to default the graphSpan and the select widget if you wanted that part to work automatically.
Well, let's admit it: it's very twitchy, but it works:
EDIT: Got rid of the twitch! The problem was that dc.js was setting the brush extent asynchronously after a little while (in response to the filter event). If we also set it during extentBrush then it never shows the wrong extent:
timeSlider.extendBrush = function() {
var extent = timeSlider.brush().extent();
if(graphSpan) {
extent[1] = moment(extent[0]).add(graphSpan, 'hours');
timeSlider.brush().extent(extent);
}
return extent;
}
https://jsfiddle.net/gordonwoodhull/xdo05chk/1/

What worked for me:
in d3:
disable resize handles
d3.selectAll('.brush>.handle').remove();
disable crosshair
d3.selectAll('.brush>.overlay').remove();
or
in css:
disable resize handles -
.handle {
pointer-events: none;
}
disable crosshair -
.overlay {
pointer-events: none;
}

Related

Changing colour of bar on selecting and unselecting bar in composite chart

https://blockbuilder.org/ninjakx/63295ea0a8052716644738d37d390e52
1)
When I click on focus ordinal bar((c2 of composite chart) it should keep the selected one as red and other as grey but it doesn't.
2)
When I click on pie chart I get red bars along with unfiltered bar(grey). Here clicking on red bar should filter other graphs it's doing that as you can see my table and pie chart is getting updated but When I click on gray bar data is also getting filtered but for pie chart it just add grey slices.
Line no. 284-324:
chart_11.fadeDeselectedArea = function (brushSelection) {
var _chart = this;
var bars = _chart.chartBodyG().selectAll('rect.bar');
if (chart_11Filter.length) {
bars.classed(dc.constants.SELECTED_CLASS, function (d) {
return chart_11Filter.includes(d.data.key);
});
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return !chart_11Filter.includes(d.data.key);
});
} else {
bars.classed(dc.constants.SELECTED_CLASS, false);
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
};
chart_11.on('pretransition', function(chart) {
chart.selectAll('rect.bar').on('click.ordinal-select', function(d) {
var i = chart_11Filter.indexOf(d.data.key);
if(i >= 0)
chart_11Filter.splice(i, 1);
else
chart_11Filter.push(d.data.key);
chart.applyFilter();
chart.redrawGroup();
});
});
If I use the above code then I get these things So I can think of these solutions.
I can change the colour of c2 bar on clicking by using the above code and applying it to c2.
also for the second graph I can use css to disable on clicking them or I
can make the filter to return none.
But when I tried the above solutions It didn't work. Problems were still the same.
If I make this function applicable only for c2 by replacing chart_11 with c2:
chart_11.fadeDeselectedArea = function (brushSelection) {
.
.
.
.
chart_11.on('pretransition', function(chart) {
.
.
.
I get this:
Edit:
chart_11.on('pretransition', function(chart) {
chart.selectAll('rect.bar').on('click', null);
If I add this I will be able to disable clicking all bar. I have to make it only for C1.
chart_11.on('pretransition', function(chart) {
// chart.selectAll('rect.bar').on('click', null);
chart.selectAll('rect.bar').on('click.ordinal-select', function(d) {
In this function my 2nd issue can be solved I guess. This function has to be customized. Accessing the child C2 and select its rect.bar and filter.
But unable to write the code for it.
This is getting to be a very hacky solution, combining two already hacky customizations of dc.js.
However, you weren't very far off; it is just a matter of restricting behaviors to c2 and cleaning out some irrelevant code.
I removed hide_second_chart because that's not necessary here, and removed the filterHandler for the same reason.
As you pointed out, fadeDeselectedArea has to be overridden on the parent; for some reason it doesn't fire on the children.
But this selection was empty, so nothing happened:
var bars = _chart.chartBodyG().selectAll('rect.bar');
I changed it to
var bars = c2.selectAll('rect.bar');
Also, the click handler should be specific to the second child, so this
chart_11.on('pretransition', function(chart) {
chart.selectAll('rect.bar').on('click.ordinal-select', function(d) {
becomes
c2.on('pretransition.click-handler', function(chart) {
chart.selectAll('.sub._1 rect.bar').on('click.ordinal-select', function(d) {
.sub._1 is CSS that will select only the second child chart.
We can use similar CSS to disable hover behaviors on the first child chart:
.dc-chart .sub._0 rect.bar:hover {
fill-opacity: 1;
}
.dc-chart .sub._0 rect.bar {
cursor: pointer;
}
Enable filterAll, as discussed in Unable to reset the focus ordinal bar chart:
chart_11.filterAll = function() {
chart_11Filter = [];
chart_11.filter(null);
};
Finally, it is confusing if the unfiltered chart is not the same color as deselected bars, so we change grey to #ccc:
.colors('#ccc')
Working fork of your block.
Hopefully the range/focus part still works, because otherwise this is making things much more complicated than they need to be!

dc.js exclude the brushed area and highlight rest

I'm not data-viz expert or d3, I have found plenty of examples to how to build brushing and zoom for example Mike.
They all have shown how to filter to the brushed area but I want to achieve to reverse of that effect, how?
Can someone through me ideas how to achieve it?
I don't know why I assumed you meant a bar chart when you linked to an area chart. You can ignore the highlighting section and skip to filtering if you're interested in doing this with line charts. There is no highlighting of line chart, just the brush itself.
Highlighting the bars in reverse
This isn't all that hard, but it's somewhat messy because we replace an undocumented function in the chart. Like most things in dc.js, if there isn't an option, you can usually replace the functionality (or add or change stuff once the chart has rendered/drawn).
Here there's a specific, public function which fades the deselected areas. It's called fadeDeselectedArea. (Actually it both fades and un-fades when the chart is ordinal, but we'll ignore that part.)
The original function looks like this:
_chart.fadeDeselectedArea = function () {
var bars = _chart.chartBodyG().selectAll('rect.bar');
var extent = _chart.brush().extent();
if (_chart.isOrdinal()) {
if (_chart.hasFilter()) {
bars.classed(dc.constants.SELECTED_CLASS, function (d) {
return _chart.hasFilter(d.x);
});
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return !_chart.hasFilter(d.x);
});
} else {
bars.classed(dc.constants.SELECTED_CLASS, false);
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
} else {
if (!_chart.brushIsEmpty(extent)) {
var start = extent[0];
var end = extent[1];
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return d.x < start || d.x >= end;
});
} else {
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
}
};
source link
We'll ignore the ordinal part because that's only individual selection, not brushed selection. Here is the reverse of the second part:
spendHistChart.fadeDeselectedArea = function () {
var _chart = this;
var bars = _chart.chartBodyG().selectAll('rect.bar');
var extent = _chart.brush().extent();
// only covering the non-ordinal (ranged brush) case here...
if (!_chart.brushIsEmpty(extent)) {
var start = extent[0];
var end = extent[1];
bars.classed(dc.constants.DESELECTED_CLASS, function (d) {
return d.x >= start && d.x < end;
});
} else {
bars.classed(dc.constants.DESELECTED_CLASS, false);
}
};
Creating a variable _chart is just to keep the code the same as much as possible. You can see that d.x >= start && d.x < end is exactly the opposite of d.x < start || d.x >= end
Reversing the filtering
We'll need to add a filterHandler to the chart in order to reverse the filtering. Again, we'll base it off the default behavior, but here there's a legitimate customization point so we don't have to replace a function, just supply one:
spendHistChart.filterHandler(function(dimension, filters) {
if(filters.length === 0)
dimension.filter(null);
else {
// assume one RangedFilter but apply in reverse
// this is less efficient than filterRange but it shouldn't
// matter much unless the data is huge
var filter = filters[0];
dimension.filterFunction(function(d) {
return !filter.isFiltered(d);
})
}
});
Again, we cut out the cases we don't care about. There is no reason to be general about something that has a specific purpose and it will only cause maintenance problems. The only two cases we care about are no filter and one range filter.
Here the RangedFilter already supplies a filter function, so we can just call it and not (!) the result. This will be slightly less efficient than the filterRange but crossfilter has no native support for multiple ranges (or the inverse of a range).
That's it! Fiddle here: http://jsfiddle.net/gordonwoodhull/46snsbc2/8/

Making SVG Responsive in React

I am working on a responsive utility component, to make a few D3 components responsive in react. However I deep SVG knowledge escapes me. I have based my responsive utility on this issue on github. However it isn't quite working, All it does is render the a chart, but not at the width or height passed in but rather at a really small width and height. It also doesn't resize.
import React from 'react';
class Responsive extends React.Component{
constructor () {
super();
this.state = {
size: {
w: 0,
h: 0
}
}
}
componentDidMount () {
window.addEventListener('resize', this.fitToParentSize.bind(this));
this.fitToParentSize();
}
componentWillReceiveProps () {
this.fitToParentSize();
}
componentWillUnmount() {
window.removeEventListener('resize', this.fitToParentSize.bind(this));
}
fitToParentSize () {
let elem = this.findDOMNode(this);
let w = elem.parentNode.offsetWidth;
let h = elem.parentNode.offsetHeight;
let currentSize = this.state.size;
if (w !== currentSize.w || h !== currentSize.h) {
this.setState({
size: {
w: w,
h: h
}
});
}
}
render () {
let {width, height} = this.props;
width = this.state.size.w || 100;
height = this.state.size.h || 100;
var Charts = React.cloneElement(this.props.children, { width, height});
return Charts;
}
};
export default Responsive;
Responsive width={400} height={500}>
<XYAxis data={data3Check}
xDataKey='x'
yDataKey='y'
grid={true}
gridLines={'solid'}>
<AreaChart dataKey='a'/>
<LineChart dataKey='l' pointColor="#ffc952" pointBorderColor='#34314c'/>
</XYAxis>
</Responsive>
disclaimer: I'm the author of vx a low-level react+d3 library full of visualization components.
You could use #vx/responsive or create your own higher-order component based on withParentSize() or withWindowSize() depending on what sizing you want to respond to (I've found most situations require withParentSize()).
The gist is you create a higher-order component that takes in your chart component and it attaches/removes event listeners for when the window resizes with a debounce time of 300ms by default (you can override this with a prop) and stores the dimensions in its state. The new parent dimensions will get passed in as props to your chart as parentWidth, parentHeight or screenWidth, screenHeight and you can set your svg's width and height attributes from there or calculate your chart dimensions based on those values.
Usage:
// MyChart.js
import { withParentSize } from '#vx/responsive';
function MyChart({ parentWidth, parentHeight }) {
return (
<svg width={parentWidth} height={parentHeight}>
{/* stuff */}
</svg>
);
}
export default withParentSize(MyChart);

cleaning axis in dynamic charts in dimple.js

I'm using the clean axis function courtesy of #JohnKiernander. This works fine with static charts. But when I have a chart that updates (in this example when a button in clicked), the clean axis function does not work as expected. The function also erases others numbers of the axis. Is there a way to make this function work with dynamic charts? or do I have to take another approach?
See fiddle: http://jsfiddle.net/jdash99/oba54L1a/ for a better explanation.
// Clean Axis Function for reference
// Pass in an axis object and an interval.
var cleanAxis = function (axis, oneInEvery) {
// This should have been called after draw, otherwise do nothing
if (axis.shapes.length > 0) {
// Leave the first label
var del = 0;
// If there is an interval set
if (oneInEvery > 1) {
// Operate on all the axis text
axis.shapes.selectAll("text").each(function (d) {
// Remove all but the nth label
if (del % oneInEvery !== 0) {
this.remove();
// Find the corresponding tick line and remove
axis.shapes.selectAll("line").each(function (d2) {
if (d === d2) {
this.remove();
}
});
}
del += 1;
});
}
}
};
I suggest switching to a method with sets opacity rather than removing the label completely. I've modified your fiddle in 2 ways. Firstly the clean axis method becomes:
var cleanAxis = function (axis, oneInEvery) {
// This should have been called after draw, otherwise do nothing
if (axis.shapes.length > 0) {
// Leave the first label
var del = 0;
// If there is an interval set
if (oneInEvery > 1) {
// Operate on all the axis text
axis.shapes.selectAll("text").each(function (d) {
d3.select(this).attr("opacity", 1);
// Remove all but the nth label
if (del % oneInEvery !== 0) {
d3.select(this).attr("opacity", 0);
}
del += 1;
});
}
}
};
also because you are animating the draws you can't draw cleanAxis straight after, you need to assign it to the afterDraw property of the series instead:
s.afterDraw = function () { cleanAxis(myAxis, 10); };
This avoids a race condition on the label creation/hiding.
Here's the updated fiddle: http://jsfiddle.net/oba54L1a/2/

Make selected color highest level in jqGrid

I change the color of some cells in the gridComplete: function(){ . This override the hover or selected color. I want to make the hover and selected colors the highest level. i.e. if I selected a colored row, it changes to the selected color.
I suppose your question continues your previous question about the the color of the some cells. I created another demo which code is longer as my previous example from my answer to your previous question.
The main problem with the setting of the color of the cell (<td> element) is that the class of cell has of course higher priority as the classes of row because by the definition of the row classes was no "!important" attribute used. So to be able to make the selected of hovered cell be exactly like other standard cells one have to remove the cell class which changes its color. After "unselecting" or "unhovering" the corresponding row one should restore the removed cell class (the 'ui-state-error ui-state-error-text' classes). I implemented this behavior with the following code:
var grid = $("#list");
var saveErrorStateInData = function(ptr) {
var redCells = $("td.ui-state-error",ptr);
if (redCells.length > 0) {
var errorCells=[];
$.each(redCells,function(index, value) {
errorCells.push(value);
$(value).removeClass("ui-state-error ui-state-error-text");
});
$(ptr).data('errorCells',errorCells);
}
};
var restoreErrorStateFromData = function(ptr) {
var errorCells = $(ptr).data('errorCells');
if (errorCells && typeof errorCells.length !== "undefined"
&& errorCells.length>0) {
$.each(errorCells,function(index, value) {
$(value).addClass("ui-state-error ui-state-error-text");
});
}
};
grid.jqGrid({
// all jqGrid parameters
beforeSelectRow: function(rowid, e) {
var selrowid = $(this).getGridParam('selrow');
restoreErrorStateFromData($("#"+selrowid)[0]);
ptr = $(e.target).closest("tr.jqgrow");
saveErrorStateInData(ptr);
return true;
}
}).bind('mouseover',function(e) {
var ptr = $(e.target).closest("tr.jqgrow");
if($(ptr).attr("class") !== "subgrid") {
$(ptr).addClass("ui-state-hover");
saveErrorStateInData(ptr);
}
return false;
}).bind('mouseout',function(e) {
var ptr = $(e.target).closest("tr.jqgrow");
var selrowid = grid.getGridParam('selrow');
$(ptr).removeClass("ui-state-hover");
if (ptr.length === 1 && ptr[0].id !== selrowid) {
restoreErrorStateFromData(ptr);
}
return false;
});
On the demo you will see how all this work.
Sorry for answering this old question, but I hope someone else might find it useful. After searching quite a while for a solution, I came up with this:
Add a dummy class (with no styles) to the column using the jqGrid colmodel option 'classes'.
Add a style setting the background using a selector like this:
tr.jqgrow:not(.ui-state-hover):not(.ui-state-highlight) td.mydummycol {
background-color: #ffd !important;
}
This way the background is only applied if the row is not selected or in the hover state.

Resources