I'm working on a project where I'm making multiple D3 stacked bar charts. The idea is that when a button is pressed, the plot will reload with a different dataset, similar to the code that is shown here.
My issue is with modifying this code to make the bar charts stacked. I'm not too familiar with the update functionality in D3 (I've never learned about it), so I've been trying to just append more "rect" objects to the "u" variable. It will load in correctly the first time (with all the "rect" objects where I'd expect), but whenever the update method is recalled on a button click all that gets drawn is the second iteration of the append "rect" calls. If anyone knows how to work this code into stacked bar chart functionality, I'd greatly appreciate it.
For reference, this is what I've been trying
u
.enter()
.append("rect") // Add a new rect for each new elements
.merge(u) // get the already existing elements as well
.transition() // and apply changes to all of them
.duration(1000)
.attr("x", function(d) { return x(d.group); })
.attr("y", function(d) { return y(d.value1); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.value1); })
.attr("fill", "#69b3a2")
u
.enter()
.append("rect") // Add a new rect for each new elements
.merge(u) // get the already existing elements as well
.transition() // and apply changes to all of them
.duration(1000)
.attr("x", function(d) { return x(d.group); })
.attr("y", function(d) { return y(d.value2 + d.value1); })
.attr("width", x.bandwidth())
.attr("height", function(d) { return height - y(d.value1); })
.attr("fill", "#69b3a2")
Related
My code works and it shows me the elements for my data, but d3 doesn't update the text of my SVG Element after changing my data and running the same code again. I have to refresh the whole site for it to change.
var blackbox= d3.select("#content")
.selectAll(".silencer")
.data([0]);
blackbox.enter()
.append("div")
.attr("class", "silencer")
.attr("id", "silencer");
blackbox.exit().remove();
var box = blackbox.selectAll(".ursa")
.data(fraung);
box.enter()
.append("div")
.attr("class", "ursa")
.each(function(d) {
d3.select(this)
.append("svg")
.attr("class", "invoker")
.each(function(d) {
d3.select(this).append("svg:image")
.attr("xlink:href", "images/qwer.png")
.attr("x", "0")
.attr("y", "0")
.attr("width", "100")
.attr("height", "100")
.append("title")
.text(function(d) {return (d.name)});
});
d3.select(this).append("div")
.attr("class", "chen")
.each(function(d) {
d3.select(this).append("table")
.attr("class", "tab")
.each(function(d) {
d3.select(this).append("tbody")
.each(function(d) {
d3.select(this).append("tr")
.text(function(d) {return("Name: ")})
.attr("class", "key")
.each(function(d) {
d3.select(this).append("td")
.text(function(d) {return (d.name)});
});
});
});
});
});
box.exit().remove();
It sounds like your SVG element isn't being cleared before you load the second data set and so the second data set is being drawn behind the first. If the only thing that is changing is the text, it would look like nothing is happening at all. A browser refresh would clear any dynamically drawn content. Before you invoke "blackbox", you can do something like this to clear everything in the "#content" element, which I'm assuming is your SVG container.
if(!d3.select("#content").empty()) d3.select("#content").remove();
This will remove the SVG container entirely. So you'll have to create it again before you can load in new data. Alternatively if you just want to remove the child elements from the SVG container, you could do this:
if(!d3.select("#content").selectAll("*").empty()) d3.select("#content").selectAll("*").remove();
I have a map and a matching legend on my website. As the user selects different values from a select list, the map is updated and in the same function, the legend should be updated with new values. As the map actualization works properly, the values of the legend stay the same even in the console are logged the right values if I log the variables.
This is the function that draws the legend:
color_domain = [wert1, wert2, wert3, wert4, wert5];
ext_color_domain = [0, wert1, wert2, wert3, wert4, wert5];
console.log(ext_color_domain);
legend_labels = ["< "+wert1, ""+wert1, ""+wert2, ""+wert3, ""+wert4, "> "+wert5];
color = d3.scale.threshold()
.domain(color_domain)
.range(["#85db46", "#ffe800", "#ffba00", "#ff7d73", "#ff4e40", "#ff1300"]);
var legend = svg.selectAll("g.legend")
.data(ext_color_domain)
.enter().append("g")
.attr("class", "legend");
var ls_w = 20, ls_h = 20;
legend.append("rect")
.attr("x", 20)
.attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
.attr("width", ls_w)
.attr("height", ls_h)
.style("fill", function(d, i) { return color(d); })
.style("opacity", 0.7);
legend.append("text")
.attr("x", 50)
.attr("y", function(d, i){ return height - (i*ls_h) - ls_h - 4;})
.text(function(d, i){ return legend_labels[i]; });
console.log(legend_labels); //gives the right legend_labels but doesn't display them correctly
};
Sadly even the map is updated with new colors they're colored with the old thresholds. This is the way the map is colored:
svg.append("g")
.attr("class", "id")
.selectAll("path")
.data(topojson.feature(map, map.objects.immoscout).features)
.enter().append("path")
.attr("d", path)
.style("fill", function(d) {
return color(rateById[d.id]);
})
This is tough to answer without a complete, working code sample but...
You are not handling the enter, update, exit pattern correctly. You never really update existing elements, you are only re-binding data and entering new ones.
Say you've called your legend function once already, now you have new data and you do:
var legend = svg.selectAll("g.legend")
.data(ext_color_domain)
.enter().append("g")
.attr("class", "legend");
This re-binds the data and computes an enter selection. It says, hey d3, what data elements are new? For those new ones, you then append a g. Further:
legend.append("rect")
.attr("x", 20)
.attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
.attr("width", ls_w)
.attr("height", ls_h)
.style("fill", function(d, i) { return color(d); })
.style("opacity", 0.7);
Again, this is operating on those newly entered elements only. The ones that already existed on the page aren't touched at all.
Untested code, but hopefully it points you in the right direction:
// selection of all enter, update, exit
var legend = svg.selectAll("g.legend")
.data(ext_color_domain); //<-- a key function would be awesome here
legend.exit().remove(); //<-- did the data go away? remove the g bound to it
// ok, what data is coming in? create new elements;
var legendEnter = legend.enter().append("g")
.attr("class", "legend");
legendEnter.append("rect");
legendEnter.append("text");
// ok, now handle our updates...
legend.selectAll("rect")
.attr("x", 20)
.attr("y", function(d, i){ return height - (i*ls_h) - 2*ls_h;})
.attr("width", ls_w)
.attr("height", ls_h)
.style("fill", function(d, i) { return color(d); })
.style("opacity", 0.7);
legend.selectall("text")
...
There's some really great tutorials on this; and it's confusing as hell, but it's the foundation of d3.
An example that helps you get started with updating d3 (d3, v4):
const line = svg.selectAll('line').data(d3Data); // binds things
line.exit().remove(); // removes old data
line.enter()
.append('line') // add new lines for new items on enter
.merge(line) // <--- this will make the updates to the lines
.attr('fill', 'none')
.attr('stroke', 'red');
I found no direct answer for this, please forgive me if this has been covered differently in another topic.
I draw a bar chart which appears with a transition. I also want to add a tooltip which displays the value of data on mousehover.
Using the code below I have managed to obtain either the tooltip or the transition, but never the 2 together, which is my objective.
chart.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("fill", function(d) {return colorscale(colorize(d.age));})
.attr("x", function(d) {return xscale(d.name);})
.attr("y", height - 3)
.attr("height", 3)
.attr("width", xscale.rangeBand())
.append("title")
.text(function(d){return d.age;})
.transition()
.duration(1600)
.attr("y", function (d) {return yscale(d.age);})
.attr("height", function (d) {return height - yscale(d.age);}) ;
If I remove
.append("title")
.text(function(d){return d.age;})
Then my transition works fine. If I but those 2 lines back I can see my tooltip but I lose my transition.
Any suggestion would be appreciated!
You can see the result here
Thank you
You need to add the transition to the rect and not the title element:
var sel = chart.selectAll(".bar")
.data(data)
.enter()
.append("rect");
sel.append("title")
.text(function(d){return d.age;});
sel.transition()
.duration(1600)
.attr("y", function (d) {return yscale(d.age);})
.attr("height", function (d) {return height - yscale(d.age);}) ;
I'm working on a d3.js pie chart application. I am trying to develop the functionality that when you click on the legend rectangles, it toggles the slice on/off as well as the fill inside the legend rectangle.
http://jsfiddle.net/Qh9X5/3136/
legend
Rects
.enter()
.append("rect")
.attr("x", w - 65)
.attr("y", function(d, i){ return i * 20;})
.attr("width", 10)
.attr("height", 10)
.style("fill", function(d, i) {
return methods.color(i);
})
.style("stroke", function(d, i) {
return methods.color(i);
})
.on('click', function(d, i){
onLegendClick(d, i);
})
Here's one way to solve your problem:
One change required in your code is to use key functions, so that d3 matches the filtered data to the corresponding DOM node. Labels seem to be a proper key in your dataset.
Simply use:
.data(this.piedata, function(d) { return d.data.label});
instead of
.data(this.piedata);
Then, in your OnLegendClick function, you want to select all the legend's rect and all the svg arcs matching with the clicked element.
Workflow is :
select the DOM elements
match with the selected data
apply changes
Here's how to do it:
function onLegendClick(dt){
d3.selectAll('rect').data([dt], function(d) { return d.data.label}).style("opacity", function(d) {return Math.abs(1-d3.select(this).style("opacity"))})
d3.selectAll('.pie').data([dt], function(d) { return d.data.label}).style("opacity", function(d) {return Math.abs(1-d3.select(this).style("opacity"))})
}
I let you adjust the "toggle" feature. You might also want to change the texts in addition to the arcs, for this use another selection.
Updated jsfiddle: http://jsfiddle.net/Qh9X5/3138/
I'm currently looking at this bar chart example.
http://jsfiddle.net/enigmarm/3HL4a/13/
In my own version I've been using a json array as the data and is structured like so.
[{"irish":"154187","non_irish":"309638","area":"Connacht"},
{"irish":"588725","non_irish":"2182932","area":"Ireland"},
{"irish":"180755","non_irish":"1017491","area":"Leinster"},
{"irish":"189395","non_irish":"672660","area":"Munster"},
{"irish":"64388","non_irish":"183143","area":"Ulster"}]
My question is how would I apply both data.irish and data.non_irish to the "y" attribute and generate bars for both as currently I can't work out how to apply both because the "y" attribute will only take one in its parameter.
var bar = svg.selectAll("rect")
.data(data)
.enter().append("g")
.attr("class", "bar");
var bartwo =bar.append("rect")
.attr("class", "bar")
.style("fill", function(d,i) {
return colours[i];
})
.attr("x", function(d,i) { return x(data[i].area); })
.attr("y", function(d,i) { return y(data[i].irish); })
.attr("width", barWidth)
.attr("height", function(d,i) { return height - y(data[i].irish); })
Any help would be truely appreciated.
This dual bar-chart might help you: http://nvd3.org/examples/multiBarHorizontal.html. It emphasizes on the contrast of the two dimensions as well as comparison of multiple groups in one dimension (E.g the number of Irish speakers in different areas).