Following image shows how I want legend items in a d3 graph to be like. All items should be aligned with one line for all items.
How do I achieve the above using d3.js?
I tried multiple times not solve this problem. I can not put put all items in a single line.
Here you go.
Just changed the x and y attributes of the legend and it did the work.
var legend = svg.append("g")
.attr("class", "legend")
.attr("x", w)
.attr("height", 50)
.attr("width", 300)
.attr("transform", "translate(" + (w - 200) + ", -50)");
Removed y and used the transform and placed the legend on top right corner.
legend.selectAll('g').data(dataset)
.enter()
.append('g')
.each(function(d, i) {
var g = d3.select(this);
g.append("rect")
.attr("x", i * 60)
.attr("y", 65)
.attr("width", 10)
.attr("height", 10)
.style("fill", color_hash[String(i)][1]);
Here I changed the x and y attribute values to get the desired out.
g.append("text")
.attr("x", i * 60 + 15)
.attr("y", 73)
.attr("height",30)
.attr("width",100)
.style("fill", color_hash[String(i)][1])
.text(color_hash[String(i)][0]);
And finally amended the text with same logic to stay inline with the legend icons.
Hope this helps you.
Related
I am trying to convert a bubble chart from d3v3 to v4. Running into x,y,d missing variables?
In this version -- a rect is applied to the svg - and then a circle is cut -- so its like an inverse bubble chart.
I am keen to work out a set radius for the chart as a maxium -- if it should act like a score between 0 and 100? What kind of math to apply that a max radius has been reached to signify that the value is very big?
I also tried to have the svg mask adapt - if the browser or its container changed size -- ideally would want it to response during the change - rather than resizeEnd
//version 3
https://jsfiddle.net/8ag1vf6e/1/
//current version 4
https://jsfiddle.net/d56g9r0y/
// filters go in defs element
var defs = innversebubble.append("defs");
var mask = defs.append("mask")
.attr("id", "myMask");
mask.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", width)
.attr("height", height)
.style("fill", "white")
.style("opacity", 1);
var invisiblebubble = mask.append("circle")
.data(data);
//create a fixed bubble first
invisiblebubble
.attr("cx", "50%")
.attr("cy", "50%")
.attr("r", function(d) {
return d.value - 20;
});
//now mask the fixed circle
var masker = defs.append(function() {
return mask.node().cloneNode(true)
})
.attr("id", "myMaskForPointer")
.select("rect")
.style("fill", "white")
.style("opacity", 1);
invisiblebubble
.attr("r", 10);
//apply the rest of the chart elements
var rect = innversebubble
.attr("class", "series")
.append("g")
.attr("transform", "translate(0,0)")
.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", "100%")
.attr("height", "100%")
.attr("mask", "url(#myMask)")
.style("fill", backcolor)
.style("opacity", backopacity);
//animate this circle
invisiblebubble
.attr("cx", "50%")
.attr("cy", "50%")
.transition()
.duration(1800)
.attr("r", 10)
.transition()
.duration(900)
.attr("r", function(d) {
return d.value;
});
latest jsfiddle - 15th June -- needs fixing
https://jsfiddle.net/xmrtahns/
"I am keen to work out a set radius for the chart as a maxium -- if it should act like a score between 0 and 100? What kind of math to apply that a max radius has been reached to signify that the value is very big?
I also tried to have the svg mask adapt - if the browser or its container changed size -- ideally would want it to response during the change - rather than resizeEnd"
I've fixed the conversion and the data source - but still need issues to resolve.
var backcolor = $this.data("color");
var backopacity = $this.data("opacity");
var width = $this.data("width");
var height = $this.data("height");
var data = [{
"label": $this.data("label-name"),
"centralLabel": $this.data("central-label"),
"xPer": $this.data("displace-left"),
"yPer": $this.data("displace-top"),
"value": $this.data("bubble-value")
}];
http://jsfiddle.net/hLymw8et/2/
--I am keen to work out a set radius for the chart as a maximum -- if it should act like a score between 0 and 100?
--What kind of math to apply that a max radius has been reached to signify that the value is very big?
--I also tried to have the svg mask adapt - if the browser or its container changed size -- ideally would want it to response during the change - rather than resizeEnd –
I'm trying to rotate rectangles according to some data. With, the following code, the rotation applies to the whole line. How can I get each "rect" to have his own rotation applied, keeping them on the same line?
let canevas = d3.select("body")
.append("svg")
.attr("width", 1000)
.attr("height", 1000);
let rectangles = d3.select("svg")
.selectAll("rect")
.data([10, 20, 30, 40])
.enter()
.append("rect")
.attr("x", (d, i) => (i * 30) + 30)
.attr("y", 20)
.attr("width", 20)
.attr("height", 20)
.attr("transform", (d) => `rotate(${d})`);
That's the normal behaviour of rotate, since the rotate function of the translate attribute rotates the elements around the origin of the coordinates system (0,0).
An easy solution is setting the positions in the same translate:
let canevas = d3.select("body")
.append("svg")
.attr("width",300)
.attr("height",100);
let rectangles = d3.select("svg")
.selectAll("rect")
.data([10,20,30,40])
.enter()
.append("rect")
.attr("width",20)
.attr("height",20)
.attr("transform", (d,i) => `translate(${(i*30)+30},30) rotate(${d})`);
<script src="https://d3js.org/d3.v4.min.js"></script>
How can I add legend to the chart (see fiddle)? I tried to define the legend as follows, but then the chart disappears (see this fiddle).
var height = 900, width = 900;
var gridSize = Math.floor(width / 42);
var legendElementWidth = gridSize*2;
var legend = svg.selectAll(".legend")
.data([0].concat(colorScaleDomain.quantiles()), function(d) { return d; });
legend.enter().append("g")
.attr("class", "legend");
legend.append("rect")
.attr("x", height)
.attr("y", function(d, i) { return legendElementWidth * (i-0.5); })
.attr("width", gridSize / 2 )
.attr("height", legendElementWidth)
.style("fill", function(d, i) { return colors[i]; });
legend.append("text")
.attr("class", "mono")
.text(function(d) { return "≥ " + Math.round(d) + "%"; })
.attr("x", (height) + gridSize)
.attr("y", function(d, i) { return legendElementWidth*i; } );
legend.exit().remove();
This is a list of the problems:
There is no colorScaleDomain.quantiles(). It should be colorScale.quantiles() instead.
The order of the elements is very important in an SVG, which has no z index. So, your legends...
legend.enter().append("g")
.attr("class", "legend");
...should come after the drawing code for the chart. But that step can even be ignored, because of the third problem:
Your legends are outside the SVG. I corrected that with:
var svg = d3.select("body").append("svg")
.attr("width", diameter + 200)//adding some space in the SVG
And some more magic numbers in the legends code. Change them accordingly (magic numbers are not a good practice in most situations).
Here is your updated fiddle: https://jsfiddle.net/hsq05oq9/
How do I position the legend above and out of the chart?
I am working in this d3 example Grouped Bar Chart
Here is my PLUNKER but the legend can overlap the graph. Ideally I would like the legend above and out of the chart.
This is my code that I have to change. I don't understand why the 0 refers to the current position.
var legend = svg.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
I can move the legend as follows: PLUNKER
.attr("transform", function(d, i) { return "translate(" + "-500," + i * 20 + ")"; }); which moves imore to the center.
I can then have the legend read from left to right as follows:
.attr("transform", function(d, i) { return "translate(" + (-700+i*100) + "," + 0 + ")"; }); I would be great if I could move this above and outside the chart as it still overlaps some of the graph.
EDIT1 PLUNKER
tks to an answer belwo. This is my attempt, which is above the chart as I would expect, but I would like the different series in the legend to appear closer together (there is too much white space). So how do I have the coloured rect and then the text beside it, but without the whitespace?
## the below is close but I am just guessing
var legendHolder = svg.append('g')
// translate the holder to the right side of the graph
.attr('transform', "translate(" + (-width) + "," + (-margin.top) + ")")
.attr('class','legendHolder')
var legend = legendHolder.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
legend.append("rect")
.attr("x", function(d,i){return (width +(150*i))})
.attr("width", 36)
.attr("height", 18)
//.style("text-anchor", "end")
.style("fill", color);
legend.append("text")
//.attr("x", width - 24)
.attr("x", function(d,i){return (width +(140*i))})
.attr("y", 9)
.attr("dy", ".35em")
//.style("text-anchor", "end")
.text(function(d) { return d; });
EDIT2 PLUNKER
This is the best I can do, but I fell I am jsut guessing, maybe I will revisit but in the meant time if anyone can beautifully explain it to me that would be greatly appreciated
var legendHolder = svg.append('g')
// translate the holder to the right side of the graph
.attr('transform', "translate(" + (-width) + "," + (-margin.top) + ")")
.attr('class','legendHolder')
var legend = legendHolder.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr('transform', function(d, i) { return "translate(" + -40*i + "," + 0 + ")"; })
.attr("width", 36)
legend.append("rect")
.attr("x", function(d,i){return (width +(150*i))})
.attr("width", 18)
.attr("height", 18)
//.style("text-anchor", "end") //"startOffset"="100%
//.style("startOffset","100%") //"startOffset"="100%
.style("fill", color);
legend.append("text")
//.attr("x", width - 24)
.attr("x", function(d,i){return (width +(150*i)+20)})
.attr("y", 9)
.attr("dy", ".35em")
//.style("text-anchor", "end")
.text(function(d) { return d; });
If you want the legend to be located outside of the graph, you just need to increase the size of the margin where you want it to be placed and translate it into position.
Right now you are positioning the individual parts of your legend based on the size of the <svg>. You can simplify this by creating a <g> that contains all of your legend elements and translating that to its desired position in the graph.
You'll need to play around with the values to get exactly what you want, but below are the values that would allow you to place the legend in the right margin.
var margin = {top: 20, right: 100, bottom: 30, left: 40};
var legendHolder = svg.append('g')
// translate the holder to the right side of the graph
.attr('transform', "translate(" + (margin.left + width) + ",0)")
var legend = legendHolder.selectAll(".legend")
.data(ageNames.slice().reverse())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
legend.append("rect")
.attr("x", 0)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", 0)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
The legend in the example appears on the right hand side, despite a transform of zero because the elements in the group have an x attribute of nearly the width of the frame (minus a small offset), pushing them to the right:
legend.append("rect")
.attr("x", width - 18)
.attr("width", 18)
.attr("height", 18)
.style("fill", color);
legend.append("text")
.attr("x", width - 24)
.attr("y", 9)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d; });
So an x transform of -500, about half your width, pulls it to the middle, as noted. Using a smaller x attribute for the legend elements might help make it clearer for setting up your legend (this is seen in the other answer), though as your comment notes, it isn't too hard to make it work as it is (just more confusing than needed).
I have a simple D3 donut diagram with a .mouseover() event that updates an SVG:text element at the center of the donut hole. It works great...
Until I encounter users with IE 9, 10 and 11. These browsers won't render the center label. Is there a way to accommodate IE and show the center label in both browsers?
The HTML page is based on HTML5BoilerPlate with the various shims to detect old browsers.
The D3 script seems pretty straight forward.
d3.json("data/census.php", function(error, dataset) {
var h = 220, w = 295;
var outerRadius = h / 2, innerRadius = w / 4;
var color = d3.scale.category20b();
var svg= d3.select("#dailycensus")
.append("svg")
.data([dataset])
.attr("width", w)
.attr("height", h)
.append("svg:g")
.attr("transform", "translate(" + outerRadius + "," + outerRadius + ")");
var arc = d3.svg.arc()
.innerRadius(innerRadius)
.outerRadius(outerRadius);
var pie = d3.layout.pie()
.value(function(d,i) { return +dataset[i].Census; });
var arcs = svg.selectAll("g.slice")
.data(pie)
.enter()
.append("svg:g")
.attr("class", "slice");
var syssum = d3.sum(dataset, function(d,i) { return +dataset[i].Census; });
var tip = d3.tip()
.attr("class", "d3-tip")
.html(String);
var formatter = d3.format(".1%");
svg.append("text")
.attr("id", "hospital")
.attr("class", "label")
.attr("y", -10)
.attr("x", 0)
.html("Health System Census"); // Default label text
svg.append("text")
.attr("id", "census")
.attr("class", "census")
.attr("y", 40)
.attr("x", 0)
.html(syssum); // Default label value
arcs.append("svg:path")
.call(tip) // Initialize the tooltip in the arc context
.attr("fill", function(d,i) { return color(i); }) // Color the arc
.attr("d", arc)
.on("mouseover", function(d,i) {
tip.show( formatter(dataset[i].Census/syssum) );
// Update the doughnut hole label with slice meta data
svg.select("#hospital").remove();
svg.select("#census").remove();
svg.append("text")
.attr("id", "hospital")
.attr("class", "label")
.attr("y", -10)
.attr("x", 0)
.html(dataset[i].Facility);
svg.append("text")
.attr("id", "census")
.attr("class", "census")
.attr("y", 40)
.attr("x", 0)
.html(+dataset[i].Census);
})
.on("mouseout", function(d) {
tip.hide();
// Return the doughnut hole label to the default label
svg.select("#hospital").remove();
svg.select("#census").remove();
svg.append("text")
.attr("id", "hospital")
.attr("class", "label")
.attr("y", -10)
.attr("x", 0)
.html("Health System Census");
svg.append("text")
.attr("id", "census")
.attr("class", "census")
.attr("y", 40)
.attr("x", 0)
.html(syssum);
})
Replace all the .html calls with .text calls. Generally innerHTML is for HTML things although browsers are giving it SVG support as everybody keeps expecting it to work.
It's not immediately clear what is causing the issue, however setting the .text property instead resolves the issue after testing with Fiddler:
svg.append("text")
.attr("id", "hospital")
.attr("class", "label")
.attr("y", -10)
.attr("x", 0)
.text(dataset[i].Facility);
svg.append("text")
.attr("id", "census")
.attr("class", "census")
.attr("y", 40)
.attr("x", 0)
.text(+dataset[i].Census);
})
After investigating the <text /> elements directly in the Developer Tools you can see that setting the .innerHTML property doesn't render the results you'd expect, however .textContent does.
If this is working as expected in both Chrome and Firefox, I'll gladly open up an interop bug for the IE team to look into. We've been doing some SVG work lately, so I may find that this has already been discussed.
I had the same issue and innerSvg polyfill helps me. Now html() in SVG works in IE.