Access parent attribute in d3.js to set attribute of child - javascript

I have (part of) HTML here:
<g style="fill: rgb(49, 130, 189);" transform="translate(0,0)" x="200" class="chr">
<circle cy="175.92776604033872" r="3"></circle>
<circle cy="292.4129588695106" r="3"></circle>
</g>
I am trying to set the cx attribute of the circles, for which I need to access to the x attibute of the parent. My code is given below:
ch.selectAll('circle')
.data((d) => {
return d.values;
})
.enter().append('circle')
.attr('r', 3)
.attr('cx', (d) => {
...
})
.attr('cy', (d) => {
return y(d.num);
});
Does anyone know how I can get the value of x attribute when setting the cx value? Thanks in advance!!

Taking into consideration #GerardoFurtado's comment, I'll assume you are stashing that x value there for other reasons then positioning...
You can access the parent (and the x attribute) as:
.attr('cx', function(d) {
var parentXValue = d3.select(this.parentNode).attr("x");
})

Related

Appending title void transition animation in Javascript

I am trying to add transition() and append("title") to allow animation and hover over tooltip at the same time on my scatterplot. But when I add transition, tooltip no longer pops out.
const circles = g.merge(gEnter).selectAll('circle').data(data);
circles
.enter().append('circle').merge(circles).transition().duration(2000)
.attr('cy', d => yScale(yValue(d)))
.attr('cx', d => xScale(xValue(d)))
.attr('r', d => (d.Score*1.29)+1)
.attr("fill", d=>colorArray(d.Type))
.append("title").text(d => (d.Country_or_region+ "\n" +"Rank: "+ d.Overall_rank))
Everything after .transition() is a transition, and there is no .append() method for a transition. If you inspect the console you'll probably see an error.
That said, if for whatever reason you want append the title only after the transition started, you can use the .on("start") method:
.on("start", function() {
d3.select(this).append("title").text("foo")
})
Here is the demo, there is no title at the beginning. After the transition starts you'll get the title when hovering over the circle:
const circle = d3.select("circle");
circle.transition()
.duration(20000)
.delay(2000)
.attr("cx", 100)
.on("start", function() {
d3.select(this).append("title").text("foo")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg>
<circle r="20" cx="20" cy="100"></circle>
</svg>

How can I dynamically resize an SVG rect based on text width?

In an SVG graph I create node elements consisting of a rectangle and some text. The amount of text can differ significantly, hence I'd like to set the width of the rect based on the width of the text.
Here's the creation of the rectangles with D3.js (using fixed width and height values):
var rects = nodeEnter.append("rect")
.attr("width", rectW)
.attr("height", rectH);
followed by the text element:
var nodeText = nodeEnter.append("text")
.attr("class", "node-text")
.attr("y", rectH / 2)
.attr("dy", ".35em")
.text(function (d) {
return d.data.name;
});
nodeText // The bounding box is valid not before the node addition happened actually.
.attr("x", function (d) {
return (rectW - this.getBBox().width) / 2;
});
As you can see, currently I center the text in the available space. Then I tried to set the widths of the rects based on their text, but I never get both, the rect element and the text HTML element (for getBBox()) at the same time. Here's one of my attempts:
rects.attr("width",
d => this.getBBox().width + 20
);
but obviously this is wrong as it refers to rects not the text.
What's the correct approach here?
I would use getComputedTextLength to measure the text. I don't know if there is an equivalent for this in D3.js My answer is using plain javascript and is assuming that the rect and the text center is {x:50,y:25 } and you are using text{dominant-baseline:middle;text-anchor:middle;}
let text_length = txt.getComputedTextLength();
rct.setAttributeNS(null,"width",text_length )
rct.setAttributeNS(null,"x",(50 - text_length/2) )
svg{border:1px solid}
text{dominant-baseline:middle;text-anchor:middle;}
<svg viewBox="0 0 100 50">
<rect x="25" y="12.5" width="50" height="25" stroke="black" fill="none" id="rct" />
<text x="50" y="25" id="txt">Test text</text>
</svg>
Alternatively instead of txt.getComputedTextLength() you may use txt.textLength.baseVal.value
The solution is pretty simple when you remember that the this binding in the attr() call refers to the associated HTML (SVG) element:
rects.attr("width",
d => this.parentNode.childNodes[1].getComputedTextLength() + 20
);
The rect is the first element in a list of SVG elements that make up the displayed node. The text for that node is at index 1 (as follows from the append calls).
Normally I would comment, but I don't have enough reputation points.
The accepted answer has the right idea, but it doesn't work, how he coded it. The first problem is, he uses an arrow function instead of an anonymus function. In arrow functions, this has a different scope. So use an anonymus function here.
The second problem is the order of rect and text, as you can see in the source code, in the question. Since rect is appended before text, the parent node doesn't have the child text yet. So you have to just append the rect, then append the text and set its attrs and then set the attrs of rect. So the solution is:
var rects = nodeEnter.append("rect")
var nodeText = nodeEnter.append("text")
.attr("class", "node-text")
.attr("y", rectH / 2)
.attr("dy", ".35em")
.text(function (d) {
return d.data.name;
});
nodeText // The bounding box is valid not before the node addition happened actually.
.attr("x", function (d) {
return (rectW - this.getBBox().width) / 2;
});
rect
.attr('width', function () {
return this.parentNode.childNodes[1].getComputedTextLength();
})
.attr("height", rectH);
Note: If you don't need the parameter d, you don't have to accept it, like I did.

D3 text positioning inside g element

I am new to D3 and I am trying to add text inside rectangle using D3 v5. I have written following code for same.
rootSVG = d3.select('.rootSVG')
.selectAll('rect')
.data(data)
.enter()
.append('g')
.attr('transform', (d, i, elements) => {
return 'translate(0, ' + i * 21 + ')';
});
rootSVG.append('rect')
.attr('height', 20)
.attr('width', 100)
.style('fill', 'green')
.on('mouseover', (d, i, elements) => {
d3.select(elements[i])
.transition()
.duration(500)
.style('fill', 'red');
})
.on('mouseout', (d, i, elements) => {
d3.select(elements[i])
.transition()
.duration(500)
.style('fill', 'green');
});
rootSVG.append('text')
.attr('x', 10)
.text((d, i, elements) => {
return d.name;
});
I am getting the following results in the browser.
As you can see in above picture, rectangle elements are getting placed fine but text elements are off. Why this behaviour is happening even though they belong to same group? How to I make sure that text always stays inside the rectangle?
JSFiddle https://jsfiddle.net/ysm0hfzn/4/
This is due to how SVG draws text.
It's somewhat different from playing with divs and all in "traditional" HTML: you could think of it as an actual graphics framework.
The problem here is that the text element's baseline is, by default, its bottom edge. Which means that, when drawing text at (0, 0), the text element's bottom-left corner will be at (0, 0)
You could change your text elements' dominant baseline by adding the following CSS to your code:
g > text {
dominant-baseline: text-before-edge;
}
This would allow your texts to be drawn inside your gs, vertically.
As a side note, the horizontal-axis equivalent of the baseline for text is determined by the text-anchor property. If you wanted to center your text inside their g, you could simply:
anchor the text elements in to their middle: text-anchor: middle
center the anchor within your g: x="50"
Here's a code snippet demonstrating how to use the properties I mentionned in your example.
g > text {
dominant-baseline: text-before-edge;
text-anchor: middle;
}
<svg>
<g>
<rect width="100" height="20" fill="LimeGreen"></rect>
<text x="50">Letter</text>
</g>
<g transform="translate(0, 22)">
<rect width="100" height="20" fill="LimeGreen"></rect>
<text x="50">Number</text>
</g>
</svg>

Can a path have 2 different fill colours at a certain point?

I have an area chart.
I would like it to change the fill colour at a certain point along the x axis.
Example: If a value is greater than a certain value, change the fill colour of the path from this point on.
I have been trying the following:
.attr("fill", function (d, i) {
if (d.timeFrom < d.beforePredictedDate ){
d3.select(this).style("fill", function (d,i) {
return "purple"
});
}
else{
d3.select(this).style("fill", function (d,i) {
return "green"
});
}
}
The ideal outcome would produce something that enables the following:
As Robert said, you can make a fill like that using a linearGradient that starts and ends at the colour boundary.
<svg>
<defs>
<linearGradient id="grad">
<stop offset="70%" stop-color="black"/>
<stop offset="70%" stop-color="limegreen"/>
</linearGradient>
</defs>
<circle cx="150" cy="75" r="75" fill="url(#grad)"/>
</svg>
But for general paths, working out where to position the gradient stops may end up being a pain. So it is probably simpler and better in most cases to use two paths - as Robert said.

How to select elements according to an attribute(fill color) in D3.js with SelectAll

I have sets of circles on a map like 10 red circles, 10 blue circles, 10 green circles. How can i select only red circles using d3 selectAll or select?
Or is there any other methods than that?
the color has been given like this(as the value of "fill" in "style" attribute,
feature = g.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("id", function (d) {
return d.ArtistID + d.FollowerID;
})
.style("stroke", "black")
.style("opacity", .6)
.style("fill", function (d) {
if (d.ArtistID == 1) {
return "red"
} else if (d.ArtistID == 2) {
return "blue"
} else {
return "green"
};
})
.attr("r", 10);
so, the circles will be drawn like this,
<circle id="10" r="10" transform="translate(695,236)" style="stroke: rgb(0, 0, 0); opacity: 0.6; fill: rgb(255, 255, 0);"></circle>
I want to select the circles of red color. Cam somebody help?
Thanks in Advance.
You're asking to select based on the value of the style attribute. The fill property is nested within the style attribute; it is not a direct attribute of the DOM node. So you won't be able to select it using an attribute selector (ie the method #LarsKotthoff linked to).
You can switch to setting the fill using the SVG fill attributes, .attr('fill', ...) instead of using style('fill'), which will allow you to later select it using an attribute selector.
That aside, selecting via the fill attribute doesn't seem too elegant. If your design evolves and you start using a different fill color, you'll have to change the attribute selector as well. Assigning it a class and selecting based on the class is more appropriate.
Perhaps the best is to select based on data. Eg:
g.selectAll('circle')
.filter(function(d) { return d.ArtistID == 1; })
.style('fill', function(d, i) {
// here you can affect just the red circles (bc their ArtistID is 1)
})

Categories