How to change the position of legend in Scatter Chart D3.js - javascript

I want to shift the legends on top of the chart
I tried using CSS position relative but seems that it does not work on SVG
please have a look at the codepen
http://codepen.io/7deepakpatil/pen/LkaKoy
var legend = svg.selectAll(".legend")
.data(color.domain())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
above is the code where the legend are being generated.
is it possible using css or please provide any d3 or JS way to fix this.

Use SVG translate. Similar to what you have but you need to apply it to the whole legend. So I appended a 'g' element, gave it an id for easy selection later and applied a translate before you appended anything to it, like so :
var legend = svg.append('g').attr('id','legendContainer')
.attr("transform", function(d) { return "translate(-200,100)"; }) //this is the translate for the legend
.selectAll(".legend")
.data(color.domain())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });
Updated codepen : http://codepen.io/anon/pen/GqLXRx

Related

Making more space for a graph legend in d3js

The names of the legend don't fully show.They are cut off, if I increase the width, the bars just grow bigger. How can I accommodate more space for my legend?
I tried appending the legend to the 'svg' tag instead of the 'g' tag but still not the desired results. I even plotted the axis, bars and legend on the 'svg' tag but its still not working.
javascript
const g= svg.append('g')
.attr("transform", `translate(${margin.left},${margin.top})`)
const xAxis= g.append('g')
.call(d3.axisBottom(x).tickSizeOuter(0))
.attr("transform", "translate(0," + innerHeight + ")")
const yAxis= g.append('g')
.call(d3.axisLeft(y).tickSizeOuter(0))
//stack the data? --> stack per subgroup
var stackedData = d3.stack()
.keys(subgroups)
(data)
var legend = g.append('g')
.attr('class', 'legend')
.attr('transform', `translate(${210},${20})`);
legend.selectAll('rect')
.data(subgroups)
.enter()
.append('rect')
.attr('x', 0)
.attr('y', function(d, i){
return i * 20;})
.attr('width', 14)
.attr('height', 14)
.attr('fill', function(d, i){
return color(i);
});
legend.selectAll('text')
.data(subgroups)
.enter()
.append('text')
.text(function(d){
return d;
})
.attr('x',18)
.attr('y', function(d, i){
return i * 18;
})
.attr('text-anchor', 'start')
.attr('alignment-baseline', 'hanging');
//below is my plotted data
telescope,allocated,unallocated
IRSF,61,28
1.9-m,89,0
1.0-m,64,23
// width=300 and heigh=300 for svg
I want to show the full names of the legends just next to the right of the bars for the graph.
Link to the graph is here.
How do I solve the problem?
Your issue is that the SVG's width is too narrow to accomodate showing all of the legend texts.
If your graph follows D3 conventions, space for elements that are auxilliary to graph itself (axis names, ticks, legends, etc.) is made using an margin object. Although I can't see how your graph is made, it looks like yours is setup to use a margin object as well. Following D3 conventions the margin values are fixed, which would explain why changing the width value just makes the bars wider yet still doesn't make space for the legend texts.
Therefore, locate the margin object and change its right value to something higher. Inspecting your example, it looks like doubling it should do it.
Hope this helps!

Interference between two graphs using 'paths'

I'm building a dashboard with a couple of d3 visualizations, which looks like:
The way I built this is by making a few div's on the page, and call the .js script inside these divs. This worked perfectly fine so far. Unfortunately I run into a problem when calling my .js file with a line graph on the right top div on my page. When I call the graph.js file, this happens:
I'm not entirely sure what's happening, but I think both the visualizations are using "path" elements, and therefore they interfere with eachother. This is the main code for the map of Europe:
//Load in GeoJSON data
d3.json("ne_50m_admin_0_countries_simplified.json", function(json) {
//Bind data and create one path per GeoJSON feature
svg.selectAll("path")
.data(json.features)
.enter()
.filter(function(d) { return d.properties.continent == 'Europe'}) //we only want Europe to be shown ánd loaded.
.append("path")
.attr("class", "border")
.attr("d", path)
.attr("stroke", "black")
.attr("fill", "#ADD8E6")
.attr("countryName", function(d){return d.properties.sovereignt})
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(d.properties.sovereignt + ', ' + getCountryTempByYear(dataset, d.properties.sovereignt, document.getElementById("selectYear").value))
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
})
.on("click", function(d){
//add/delete country to/from selected countries
updateSelectedCountries(d.properties.sovereignt);
//draw the temperature visualizations again
redrawTemp(getCountryTempByYear(dataset, selectedCountries[0], document.getElementById("selectYear").value), getCountryTempByYear(dataset, selectedCountries[1], document.getElementById("selectYear").value));
//update header from the webpage
d3.select("#header").text("Climate Change: 1840-2013. Currently viewing: " + selectedCountries + ", " + document.getElementById("selectYear").value + '.');
console.log(selectedCountries);
});
});
And this is the code for the line graph:
// set the dimensions and margins of the grap
var array = [[1850, 11.1], [1851, 11.7], [1852, 12.2], [1853, 11.1], [1854, 11.7], [1855, 12.2], [1856, 13.4]]
var array2 = [[1850, 14.1], [1851, 17.7], [1852, 22.2], [1853, 13.1], [1854, 24.7], [1855, 19.2], [1856, 13.4]]
// set the ranges
var x = d3.scaleLinear().range([0, 200]);
var y = d3.scaleLinear().range([200, 0]);
// define the line
var valueline = d3.line()
.x(function(d, i) { return x(array[i][0]); })
.y(function(d, i) { return y(array[i][1]); })
.curve(d3.curveMonotoneX); //smooth line
var valueline2 = d3.line()
.x(function(d, i) { return x(array2[i][0]); })
.y(function(d, i) { return y(array2[i][1]); })
.curve(d3.curveMonotoneX); //smooth line
var svg = d3.select("#div2")
.append("svg")
.attr("width", 200)
.attr("height", 200)
.attr("id", "graph");
x.domain([1850, 1856]);
y.domain([10, 25]);
array.forEach(function(data, i){
svg.append("path")
.data([array])
.attr("class", "line")
.attr("d", valueline);
})
array2.forEach(function(data, i){
svg.append("path")
.data([array2])
.attr("class", "line")
.attr("d", valueline2);
})
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + 200 + ")")
.call(d3.axisBottom(x));
// Add the Y Axis
svg.append("g")
.call(d3.axisLeft(y));
As I said, I'm not entirely sure it's because of the graphs both using the "path" element, it could be something different too. Now what I'm wondering is: what is interfering with eachother? And how can I prevent this?
I can imagine something like a filter needs to be applied, but I'm not sure how to apply this to the right "path" elements.
Any help is highly appreciated!
When you create a new chart you should create a new variable to associate with it.
In your case, this might be happening due to the reuse of the variable var svg =....
Create one variable for each chart should be enough.

Javascript/d3 passing a function parameter to an inner, anonymous function

My Javascript skills are fairly basic but advanced enough to get me to a position where I am able to design some relatively complex charts using the d3 library. I've now got to the point where I am looking to make some of my code reusable and this is where I've come across the first hurdle that the excellent api documentation can't get me past.
As an example, in the majority of my charts I want to add a legend. I have some basic code that adds a svg group for the legend which looks like this
var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function(d){return d.FIELDNAME;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
what I'd like to be able to do is add a parameter to a function which allows me to set what field from the dataset is used in the legend. Something like the below... but that actually works :)
function addLegend(legendKey) {
var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function(d){return d.legendKey;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
// rest of the legend code
}
called by
addLegend("FIELDNAME");
Lastly, understandably (perhaps) this didn't work either
function helper(legendKey){
return legendKey;
}
function addLegend(helper) {
var legend = chartContainer.selectAll(".legend")
.data(d3.map(data, function test (d, addLegend){return d.addLegend;}).keys())
.enter().append("g")
.attr("class", "legend")
.attr("transform", function(d, i) { return "translate(0," + (((height/3)) + (i*20)) + ")"; });
// rest of the legend code
}
addLegend(helper("agent"))
Any help would be greatly appreciated.

Placing labels at the center of nodes in d3.js

I am starting with d3.js, and am trying to create a row of nodes each of which contains a centered number label.
I am able to produce the desired result visually, but the way I did it is hardly optimal as it involves hard-coding the x-y coordinates for each text element. Below is the code:
var svg_w = 800;
var svg_h = 400;
var svg = d3.select("body")
.append("svg")
.attr("width", svg_w)
.attr("weight", svg_h);
var dataset = [];
for (var i = 0; i < 6; i++) {
var datum = 10 + Math.round(Math.random() * 20);
dataset.push(datum);
}
var nodes = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(dataset)
.enter()
.append("circle")
.attr("class", "node")
.attr("cx", function(d, i) {
return (i * 70) + 50;
})
.attr("cy", svg_h / 2)
.attr("r", 20);
var labels = svg.append("g")
.attr("class", "labels")
.selectAll("text")
.data(dataset)
.enter()
.append("text")
.attr("dx", function(d, i) {
return (i * 70) + 42
})
.attr("dy", svg_h / 2 + 5)
.text(function(d) {
return d;
});
The node class is custom CSS class I've defined separately for the circle elements, whereas classes nodes and labels are not explicitly defined and they are borrowed from this answer.
As seen, the positioning of each text label is hard-coded so that it appears at the center of the each node. Obviously, this is not the right solution.
My question is that how should I correctly associate each text label with each node circle dynamically so that if the positioning of a label changes along with that of a circle automatically. Conceptual explanation is extremely welcome with code example.
The text-anchor attribute works as expected on an svg element created by D3. However, you need to append the text and the circle into a common g element to ensure that the text and the circle are centered with one another.
To do this, you can change your nodes variable to:
var nodes = svg.append("g")
.attr("class", "nodes")
.selectAll("circle")
.data(dataset)
.enter()
// Add one g element for each data node here.
.append("g")
// Position the g element like the circle element used to be.
.attr("transform", function(d, i) {
// Set d.x and d.y here so that other elements can use it. d is
// expected to be an object here.
d.x = i * 70 + 50,
d.y = svg_h / 2;
return "translate(" + d.x + "," + d.y + ")";
});
Note that the dataset is now a list of objects so that d.y and d.x can be used instead of just a list of strings.
Then, replace your circle and text append code with the following:
// Add a circle element to the previously added g element.
nodes.append("circle")
.attr("class", "node")
.attr("r", 20);
// Add a text element to the previously added g element.
nodes.append("text")
.attr("text-anchor", "middle")
.text(function(d) {
return d.name;
});
Now, instead of changing the position of the circle you change the position of the g element which moves both the circle and the text.
Here is a JSFiddle showing centered text on circles.
If you want to have your text be in a separate g element so that it always appears on top, then use the d.x and d.y values set in the first g element's creation to transform the text.
var text = svg.append("svg:g").selectAll("g")
.data(force.nodes())
.enter().append("svg:g");
text.append("svg:text")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
text.attr("transform", function(d) {
return "translate(" + d.x + "," + d.y + ")";
});
The best answer came from the asker himself:
just a further observation: with only .attr("text-anchor", "middle")
for each text element, the label is at the middle horizontally but
slightly off vertically. I fixed this by adding attr("y", ".3em")
(borrowed from examples at d3.js website), which seems to work well
even for arbitrary size of node circle. However, what exactly this
additional attribute does eludes my understanding. Sure, it does
something to the y-coordinate of each text element, but why .3em in
particular? It seems almost magical to me...
Just add .attr("text-anchor", "middle") to each text element.
Example:
node.append("text")
.attr("x", 0)
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(function(d) { return d.name; });
This page describes what's going on under the svg hood when it comes to text elements. Understanding the underlying machinery and data structures helped me get a better handle on how I had to modify my code to get it working.

Nested SVG node creation in d3.js

I'v just started playing with d3js and find it strange that I have to create multiple selectors for each element I want to link to the background data structure for example separate selectors such as one for overlay text and one for rectangles to make an annotated bar graph.
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr('y',function(d,i){return i*10;})
.attr('height',10)
.attr('width',function(d){return d.interestingValue})
.fill('#00ff00');
svg.selectAll("text")
.data(data)
.enter()
.append("text")
.attr('y',function(d,i){return i*10;})
.fill('#0000ff')
.text(function(d){return d.interestingValue});
Is there a more convenient way of combining these into a single selection and enter() chain that creates both the rects and the text elements?
Use a G (group) element. Use a single data-join to create the G elements, and then append your rect and text element. For example:
var g = svg.selectAll("g")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(0," + i * 10 + ")"; });
g.append("rect")
.attr("height", 10)
.attr("width", function(d) { return d.interestingValue; });
g.append("text")
.text(function(d) { return d.interestingValue; });

Categories

Resources