set d3 zoom scaleExtent to positive values - d3.js

Well, first of all, here is a jsfiddle to illustrate what I would like to ask
So I am trying to implement a zoom behaviour. I managed to limit the zooming by setting a translate to the zoom function, (which I don't really quite understand, Just got it from another SO question), and a scaleExtent([1,10]) on the zoom behaviour
So this is the zoom behavior:
zoom = d3.behavior.zoom()
.x(xScale)
.y(yScale)
.scaleExtent([1, 10])
.on("zoom", zoomed)
and this is the zoomed function:
zoomed = ->
t = zoom.translate()
s = zoom.scale()
tx = t[0]
ty = t[1]
tx = Math.min(0, Math.max(w * (1-s), t[0]))
ty = Math.min(0, Math.max((h-padding) * (1-s), t[1]))
zoom.translate([tx, ty])
svgContainer.select("g.x.axis").call xAxis
svgContainer.select("g.y.axis").call yAxis
svgContainer.selectAll("line.matched_peak")
.attr("x1", (d) -> return xScale(d.m_mz) )
.attr("y1", h - padding)
.attr("x2", (d) -> return xScale(d.m_mz) )
.attr("y2", (d) -> return yScale(d.m_intensity) )
However, setting the scaleExtent to
.scaleExtent([1, 10]) ,
makes that one particular point with a value of 1 in the y scale is never going to be displayed (first one on the left in the jsfiddle).
But setting
.scaleExtent([0, 10])
disables the limit to zoom, and the user may zoom and pan below 0 in the y axis.
Also tried .scaleExtent([0.1, 10]) but this also allows zoom and pan below 0.
So How could I allow zoom only to positive values from 0 (including a value of 1) ?
And what function can be used to avoid the lines show beyond the axis? Is not that implicit when I use the translate function in the zoom?

The scale proceeds in a geometric series -- that is, the scale step before 1 is not 0, but 0.5. Limiting your scale extent to
.scaleExtent([0.5, 10])
should do what you want. I've also added .nice() to your scale definitions to get round numbers at the ends.
As for the clipping, no, this is not implicit in the translation. You need to clip explicitly using a clip path, which in your case can be defined as follows.
cp = svgContainer.append("defs").append("clipPath").attr("id", "cp")
.append("rect")
.attr("x", padding)
.attr("y", padding)
.attr("width", w - 2 * padding)
.attr("height", h - 2 * padding)
All you then need to do is use it when adding the elements:
msBars = svgContainer.selectAll('line.matched_peak')
.data(jsonFragmentIons)
.enter()
.append("line")
.attr("clip-path", "url(#cp)")
Complete example here.

Related

D3 zoom breaks mouse wheel zooming after using zoomIdentity

When I use d3-zoom and programatically call the scaleTo function using zoomIdentity I cannot zoom using the mouse wheel anymore.
How do I fix this issue?
https://observablehq.com/d/8a5dfbc7d858a16b
// mouse wheel zoom not working because use of zoomIdentity
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.style("display", "block");
const zoom = d3Zoom.zoom()
svg.call(zoom);
const zoomArea = svg.append('g');
zoom.on('zoom', (e) => {
zoomArea.attr("transform", e.transform)
})
zoomArea.append('circle')
.attr("cx", width/2)
.attr("cy", height/2)
.attr("r", 20)
zoom.scaleTo(svg, d3Zoom.zoomIdentity)
return svg.node();
}
The second parameter of zoom.scaleTo(svg, d3Zoom.zoomIdentity) accepts a k scaling factor (e.g., 2 for 2x zoom). The method zoom.scaleTo is intended to be used when you want to set the zoom level, but not the translation (x and y positions).
If you want to set the whole transform to the zoom identity (which resets both the zoom level and the x and y positions), the method is zoom.transform(svg, d3Zoom.zoomIdentity).
If you indeed just want to reset the scale, you can use zoom.scaleTo(svg, d3Zoom.zoomIdentity.k), or simply zoom.scaleTo(svg, 1).

Add text in rect svg and append it to arc in donut chart

I wanted to add labels to each arc in donut chart. I've added by taking the centroid of each arc and adding, but somehow it is not adding in correct position. I can't figure it out so I need some help regarding it. I've added my code in codepen. The link is here.
My donut should look like this.
Sample code is:
svg.selectAll(".dataText")
.data(data_ready)
.enter()
.each(function (d) {
var centroid = arc.centroid(d);
d3.select(this)
.append('rect')
.attr("class", "dataBG_" + d.data.value.label)
.attr('x', (centroid[0]) - 28)
.attr('y', (centroid[1]) - 5)
.attr('rx', '10px')
.attr('ry', '10px')
.attr("width", 50)
.attr("height", 20)
.style('fill', d.data.value.color)
.style("opacity", 1.0);
d3.select(this)
.append('text')
.attr("class", "dataText_" + d.data.value.label)
.style('fill', 'white')
.style("font-size", "11px")
.attr("dx", (centroid[0]) - 7)
.attr("dy", centroid[1] + 7)
.text(Math.round((d.data.value.value)) + "%");
});
Thanks in advance.
The difference between the "bad" state on codepen and the desired state is that in the one you don't like, you take the centroid and then you center your text on it. The centroid of a thick arc is the midpoint of the arc that runs from the midpoint of one line-segment cap to the other. This is roughly "center of mass" of the shape if it had some finite thickness and were a physical object. I don't think it's what you want. What you want is the midpoint of the outer arc. There's no function to generate it, but it's easy enough to calculate. Also, I think you want to justify your text differently for arcs whose text-anchor point is on the left hand of the chart from those on the right half. I'm going copy your code and modify it, with comments explaining.
// for some reason I couldn't get Math.Pi to work in d3.js, so
// I'm just going to calculate it once here in the one-shot setup
var piValue = Math.acos(-1);
// also, I'm noting the inner radius here and calculating the
// the outer radius (this is similar to what you do in codepen.)
var innerRadius = 40
var thickness = 30
var outerRadius = innerRadius + thickness
svg.selectAll(".dataText")
.data(data_ready)
.enter()
.each(function (d) {
// I'm renaming "centroid" to "anchor - just a
// point that relates to where you want to put
// the label, regardless of what it means geometrically.
// no more call to arc.centroid
// var centroid = arc.centroid(d);
// calculate the angle halfway between startAngle and
// endAngle. We can just average them because the convention
// seems to be that angles always increase, even if you
// if you pass the 2*pi/0 angle, and that endAngle
// is always greater than startAngle. I subtract piValue
// before dividing by 2 because in "real" trigonometry, the
// convention is that a ray that points in the 0 valued
// angles are measured against the positive x-axis, which
// is angle 0. In D3.pie conventions, the 0-angle points upward
// along the y-axis. Subtracting pi/2 to all angles before
// doing any trigonometry fixes that, because x and y
// are handled normally.
var bisectAngle = (d.startAngle + d.endAngle - piValue) / 2.0
var anchor = [ outerRadius * Math.cos(bisectAngle), outerRadius * Math.sin(bisectAngle) ];
d3.select(this)
.append('rect')
.attr("class", "dataBG_" + d.data.value.label)
// now if you stopped and didn't change anything more, you'd
// have something kind of close to what you want, but to get
// it closer, you want the labels to "swing out" from the
// from the circle - to the left on the left half of the
// the chart and to the right on the right half. So, I'm
// replacing your code with fixed offsets to code that is
// sensitive to which side we're on. You probably also want
// to replace the constants with something related to the
// the dynamic size of the label background, but I leave
// that as an "exercise for the reader".
// .attr('x', anchor[0] - 28)
// .attr('y', anchor[1] - 5)
.attr('x', anchor[0] < 0 ? anchor[0] - 48 : anchor[0] - 2)
.attr('y', anchor[1] - 10
.attr('rx', '10px')
.attr('ry', '10px')
.attr("width", 50)
.attr("height", 20)
.style('fill', d.data.value.color)
.style("opacity", 1.0);
d3.select(this)
.append('text')
.attr("class", "dataText_" + d.data.value.label)
.style('fill', 'white')
.style("font-size", "11px")
// changing the text centering code to match the box
// box-centering code above. Again, rather than constants,
// you're probably going to want something a that
// that adjusts to the size of the background box
// .attr("dx", anchor[0] - 7)
// .attr("dy", anchor[1] + 7)
.attr("dx", anchor[0] < 0 ? anchor[0] - 28 : anchor[0] + 14)
.attr("dy", anchor[1] + 4)
.text(Math.round((d.data.value.value)) + "%");
});
I tested. this code on your codepen example. I apologize if I affected your example for everyone - I'm not familiar with codepen and I don't know the collaboration rules. This is all just meant by way of suggestion, it can be made a lot more efficient with a few tweaks, but I wanted to keep it parallel to make it clear what I was changing and why. Hope this gives you some good ideas.

D3js Zoom With Manually Drawn Circle

I am working on a d3 scatter plot where an area of the chart will be circled (a Youden Plot). Based on available samples, I have been able to add zoom to both my data points and my axis. However, I am unable to get the circle to zoom correctly.
I suspect that I need to set up some kind of scale (scaleSqrt, possibly), but I am struggling to find documentation on this that is written at a beginner level.
My current circle code is very straightforward
var circle = drawCircle();
function drawCircle() {
return svg
.append('g')
.attr('class', 'scatter-group')
.append('circle')
.attr("r", 75 )
.attr('cx', 200 + margin.left) //suspect this needs to be related to a scale
.attr('cy', 200 + margin.top) //suspect this needs to be related to
.attr('r', 75)//suspect this needs to be related to a scale
.attr('stroke', 'red')
.attr('stroke-width', 3)
.style('fill', 'none')
}
As is the zoomed function
function zoomed() {
var new_xScale = d3.event.transform.rescaleX(xScale);
var new_yScale = d3.event.transform.rescaleY(yScale);
// update axes
gX.call(xAxis.scale(new_xScale));
gY.call(yAxis.scale(new_yScale));
//redraw data ppints
points.data(data)
.attr('cx', function(d) {return new_xScale(d.x)})
.attr('cy', function(d) {return new_yScale(d.y)});
//redraw circle
}
My work in progress is available in this fiddle . Can someone possible point me in the right direction?
I believe this will get you most of the way there. You need to update your circle attributes in the zoomed function along with the other elements:
function zoomed() {
var new_xScale = d3.event.transform.rescaleX(xScale);
var new_yScale = d3.event.transform.rescaleY(yScale);
// update axes
gX.call(xAxis.scale(new_xScale));
gY.call(yAxis.scale(new_yScale));
//redraw data ppints
points.data(data)
.attr('cx', function(d) {return new_xScale(d.x)})
.attr('cy', function(d) {return new_yScale(d.y)});
// The new part:
// the transform
let trans = d3.event.transform
// the approximate domain value of the circle 'cx' for converting later
let cx_domain = xScale.invert(200 + margin.left)
// the approximate domain value of the circle 'cy' for converting later
let cy_domain = yScale.invert(200 + margin.top)
// the circle
let circ = d3.select('.scatter-group circle')
// the radius
let rad = 75
// reset the circle 'cx' and 'cy' according to the transform
circ
.attr('cx',function(d) { return new_xScale(cx_domain)})
.attr('cy',function(d) { return new_yScale(cy_domain)})
// reset the radius by the scaling factor
.attr('r', function(d) { return rad*trans.k })
}
See this fiddle
You'll notice the circle does not scale or move at quite the same rate as the scatter dots. This is possibly because of the use of the invert function, because the conversion from range to domain and back to range is imperfect. This issue is documented
For a valid value y in the range, continuous(continuous.invert(y)) approximately equals y; similarly, for a valid value x in the domain, continuous.invert(continuous(x)) approximately equals x. The scale and its inverse may not be exact due to the limitations of floating point precision.
Your original idea to assign dynamic values to cx, cy and r will likely compensate for this, because you can then avoid the inversion.

How to get the result of zoom.translate() without altering the sensibility of panning?

I have a D3.js draw in a svg and I want to be able to pan and zoom on it. I also want a rectangle to be drawn around the initial window. I want the rectangle to become smaller as I zoom out, larger as I zoom in and to move normally as I pan around. Usual stuff.
I also want to be able to redraw the rectangle to make it fit again the actual window (so it will be smaller than the first if I zoomed in between the redraw for example). I didn't included this part in the code example but it explains why I need a way to get the zoom properties.
To properly trace the rectangle I found the zoom.translate() and zoom.scale() property, supposed to give me the parameters I need to calculate the coordinates of the rectangle's parts. However since I added this part to my code the panning sensibility became to shift as I zoom in and out: The more I zoom in, the less sensible is the panning, and the more I zoom out the more sensible it becomes.
In my mind, zoom.translate() and zoom.scale() were only supposed to fetch the parameters, not to change the way zooming and panning work, how can I fix that?
I also have inexplicably a rectangle that doesn't fit the window: it is a bit larger and shorter.
Here my piece of code:
var svg;
var map;
var zoom;
var graph = d3.select("#graph");
zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.on("zoom", function () {
svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
});
svg = graph.append("svg")
.attr("width",window.innerWidth)
.attr("height",window.innerHeight)
.call(zoom);
map = svg.append("g");
Here is the acquisition of the rectangle's coordinates:
var w_b = {
x_min: (0 - zoom.translate()[0])/zoom.scale(),
x_max: (svg.attr("width") - zoom.translate()[0])/zoom.scale(),
y_min: (0 - zoom.translate()[1])/zoom.scale(),
y_max: (svg.attr("height") - zoom.translate()[1])/zoom.scale()
And here is the drawing of the rectangle:
map.selectAll("line").remove();
map.append("line").attr("x1", w_b['x_min']).attr("x2", w_b['x_max']).attr("y1", w_b['y_min']).attr("y2", w_b['y_min'])
.attr("stroke-width", 1).attr("stroke", "black");
map.append("line").attr("x1", w_b['x_min']).attr("x2", w_b['x_max']).attr("y1", w_b['y_max']).attr("y2", w_b['y_max'])
.attr("stroke-width", 1).attr("stroke", "black");
map.append("line").attr("x1", w_b['x_min']).attr("x2", w_b['x_min']).attr("y1", w_b['y_min']).attr("y2", w_b['y_max'])
.attr("stroke-width", 1).attr("stroke", "black");
map.append("line").attr("x1", w_b['x_max']).attr("x2", w_b['x_max']).attr("y1", w_b['y_min']).attr("y2", w_b['y_max'])
.attr("stroke-width", 1).attr("stroke", "black");
As a bonus question, this doesn't work at all on Chrome, any idea about what it could be ?
To work correctly, the zoom must be defined like this:
zoom = d3.behavior.zoom()
.translate([0, 0])
.scale(1)
.on("zoom", function () {
map.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")");
});
Notice the "map.attr" instead of "svg.attr".
However it doesn't solve the issues about the size of the window and the fact it's not working on Chrome.

Modifiying dimple layout grouped chart

I am using the same chart as below. I want to push the x-axis headers i.e. Regular, Premium, Budget little bit below i.e. top padding or margin. Give some styling to it like give background color and change text color. I tried using fill and it does not work as desired. I would like to hide Price Tier/Channel also
http://dimplejs.org/examples_viewer.html?id=bars_vertical_grouped
These are SVG text elements so there is no top-padding or margin. You can move them down a bit by increasing the y property though, running the following after you call the chart.draw method will move the labels down 5 pixels:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.attr("y", function (d) {
// Get the y property of the current shape and add 5 pixels
return parseFloat(d3.select(this).attr("y")) + 5;
});
To change the text colour you need to use the fill property (again that's an svg text thing):
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.style("fill", "red");
To colour the background of the text is a little less trivial, there actually isn't a thing for that in SVG, however you can insert a rectangle behind the text and do what you like with it:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
// Iterate each shape matching the selector above (all the x axis labels)
.each(function () {
// Select the shape in the current iteration
var shape = d3.select(this);
// Get the bounds of the text (accounting for font-size, alignment etc)
var bounds = shape.node().getBBox();
// Get the parent group (this the target for the rectangle to make sure all its transformations etc are applied)
var parent = d3.select(this.parentNode);
// This is just the number of extra pixels to add around each edge as the bounding box is tight fitting.
var padding = 2;
// Insert a rectangle before the text element in the DOM (SVG z-position is entirely determined by DOM position)
parent.insert("rect", ".dimple-custom-axis-label")
// Set the bounds using the bounding box +- padding
.attr("x", bounds.x - padding)
.attr("y", bounds.y - padding)
.attr("width", bounds.width + 2 * padding)
.attr("height", bounds.height + 2 * padding)
// Do whatever styling you want - or set a class and use CSS.
.style("fill", "pink");
});
These three statements can all be chained together so the final code will look a bit like this:
d3.selectAll(".dimple-axis-x .dimple-custom-axis-label")
.attr("y", function (d) { return parseFloat(d3.select(this).attr("y")) + 5; })
.style("fill", "red")
.each(function () {
var shape = d3.select(this);
var bounds = shape.node().getBBox();
var parent = d3.select(this.parentNode);
var padding = 2;
parent.insert("rect", ".dimple-custom-axis-label")
.attr("x", bounds.x - padding)
.attr("y", bounds.y - padding)
.attr("width", bounds.width + 2 * padding)
.attr("height", bounds.height + 2 * padding)
.style("fill", "pink");
});
FYI the dimple-custom-axis-label class was added in a recent release of dimple so please make sure you are using the latest version. Otherwise you'll have to find an alternative selector

Resources