Add labels to D3 line - javascript

I want to add labels that show the values on a line chart and can't figure out how to do this.
var svg = d3.select('svg')
.attr("width", width)
.attr("height", height);
var g = svg.append("g")
.attr("transform", "translate(" + 0 + "," + 0 + ")");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.date)})
.y(function(d) { return y(d.value)})
x.domain(d3.extent(data, function(d) { return d.date }));
y.domain(d3.extent(data, function(d) { return d.value }));
I don't know how to add labels, like here for example (though my case is simpler, because I have only one chart)

I've generated some random data here. Relevant code to add the text labels:
g.selectAll('.textLabels')
.data(data).enter()
.append('text')
.classed('textLabels', true)
.attr('x', function(d) { return x(d.date); })
.attr('y', function(d) { return y(d.value); })
.text(function(d) { return d.value; });
which are positioned based on x(date) and y(value) values in the data array. You can adjust the offsets using dx, dy attributes and use some styles to fill/stroke the text.
var data = [];
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
for(var i=0; i<20; i++) {
var obj = {};
obj.date = randomDate(new Date(2018, 01,01), new Date());
obj.value = Math.floor(Math.random() * 50);
data.push(obj);
}
data.sort(function(a, b) {
return a.date > b.date ? -1 : 1;
})
var width = 800, height = 400;
var svg = d3.select('svg')
.attr("width", width)
.attr("height", height);
var g = svg.append("g")
.attr("transform", "translate(" + 0 + "," + 0 + ")");
var x = d3.scaleTime()
.rangeRound([0, width]);
var y = d3.scaleLinear()
.rangeRound([height, 0]);
var line = d3.line()
.x(function(d) {
return x(d.date)
})
.y(function(d) {
return y(d.value)
})
x.domain(d3.extent(data, function(d) {
return d.date
}));
y.domain(d3.extent(data, function(d) {
return d.value
}));
g.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("stroke-width", 1.5)
.attr("d", line);
g.selectAll('.textLabels')
.data(data).enter()
.append('text')
.classed('textLabels', true)
.attr('x', function(d) { return x(d.date); })
.attr('y', function(d) { return y(d.value); })
.text(function(d) { return d.value; });
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg></svg>
Let me know if you have any questions. Hope this helps.:)

Related

D3.js v5 Line chart with circle markers

The lines on my chart are displaying with a weird black filled-in shape instead of an actual line. Any idea what i'm doing wrong? The data is parsed in from a csv. It's a multiline chart where each series is a column in the csv(columns are: date, cat1, cat2, cat3, cat4).
Aside - I got this to work in a different fashion by defining each valueline and appending to the path. But I ran into issues with scaling the axis. I eventually need to have four plots on my html page, each with different axis scales (for example log scale on the y axis). Therefore I'll need y = d3.scaleLog().domain(my domain).range(range) and then in d3.line.y return y(my value).
var margin = {top: 20, right: 20, bottom: 30, left: 50},
w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
var padding =20;
var xScale = d3.scaleTime()
.domain([d3.min(dataset,function (d) { return d.date }),d3.max(dataset,function (d) { return d.date }) ]).range([padding, w - padding * 2])
var yScale = d3.scaleLinear()
.domain([0, d3.max(dataset,function (d) { return d.cat1 }) ]).range([h- padding, padding])
var xAxis = d3.axisBottom().scale(xScale);
var yAxis = d3.axisLeft().scale(yScale);
var svg1 = d3.select("body").append("svg")
.attr("width", w + margin.left + margin.right)
.attr("height", h + margin.top + margin.bottom)
.append("g")
.attr("transform",
"translate(" + margin.left + "," + margin.top + ")");
var line = d3.line()
.x(function(d) { return xScale(d['date']); })
.y(function(d) { return yScale(d['cat1']); });
var line2 = d3.line()
.x(function(d) { return xScale(d['date']); })
.y(function(d) { return yScale(d['cat2']); });
var line3 = d3.line()
.x(function(d) { return xScale(d['date']); })
.y(function(d) { return yScale(d['cat3']); });
var line4 = d3.line()
.x(function(d) { return xScale(d['date']); })
.y(function(d) { return yScale(d['cat4']); });
var path = svg1.append('path').attr('d', line(dataset));
var path2 = svg1.append('path').attr('d', line2(dataset));
var path3 = svg1.append('path').attr('d', line3(dataset));
var path4 = svg1.append('path').attr('d', line4(dataset));
//draw points
var selectCircle = svg1.selectAll(".circle")
.data(dataset)
selectCircle.enter().append("circle")
.attr("class", "circle")
.attr("r", 10)
.attr("cx", function(d) {
return xScale(d.date)
})
.attr("cy", function(d) {
return yScale(d.cat1)
})
.attr("fill", "#FFC300")
selectCircle.enter().append("circle")
.attr("class", "circle")
.attr("r", 10)
.attr("cx", function(d) {
return xScale(d.date)
})
.attr("cy", function(d) {
return yScale(d.cat2)
})
.attr("fill", "#FF5733")
selectCircle.enter().append("circle")
.attr("class", "circle")
.attr("r", 10)
.attr("cx", function(d) {
return xScale(d.date)
})
.attr("cy", function(d) {
return yScale(d.cat3)
})
.attr("fill", "#C70039")
selectCircle.enter().append("circle")
.attr("class", "circle")
.attr("r", 10)
.attr("cx", function(d) {
return xScale(d.date)
})
.attr("cy", function(d) {
return yScale(d.cat4)
})
.attr("fill", "#900C3F")
svg1.append("g").attr("class", "axis").attr("transform", "translate(0," + (h - padding) + ")").call(xAxis);
//draw Y axis
svg1.append("g").attr("class", "axis").attr("transform", "translate(" + padding + ",0)").call(yAxis);
// add label
svg1.append("text").attr("x", (w/2)).attr("y", h+30).attr("text-anchor", "middle").text("Year");
svg1.append("text").attr("x", padding).attr("y", padding-20).attr("text-anchor", "middle").text("# of Events");
//add title
svg1.append("text").attr("x", (w/2)).attr("y", padding).attr("text-anchor", "middle").text("Events per Year by Category");

d3 v4 Stacked to Grouped Bar Chart from CSV

Reference Mike Bostick's Stacked to Grouped Bar Chart example, I am modifying it to work with a CSV file. I have been working on this for a couple weeks and have looked through countless examples on Stack Overflow and elsewhere and am stumped.
The stacked bar chart works.
Stacked Bar Chart:
When I transition to a grouped bar chart I am only having issues referencing the key or series that is stacked or grouped. Right now all the rectangles display on top of each other instead of next to each other.
Grouped Bar Chart:
In the function transitionStep2() I want to multiply by a number corresponding to the series or key. I am currently multiplying by the number 1 in this function as a placeholder .attr("x", function(d) { return x(d.data.Year) + x.bandwidth() / 7 * 1; }).
<!DOCTYPE html>
<script src="https://d3js.org/d3.v4.min.js"></script>
<html><body>
<form>
<label><input type="radio" name="mode" style="margin-left: 10" value="step1" checked>1</label>
<label><input type="radio" name="mode" style="margin-left: 20" value="step2">2</label>
</form>
<svg id = "bar" width = "500" height = "300"></svg>
<script>
var svg = d3.select("#bar"),
margin = {top: 20, right: 20, bottom: 20, left: 20},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.08);
var y = d3.scaleLinear()
.range([height, 0]);
var color = d3.scaleOrdinal()
.range(["#7fc97f", "#beaed4", "#fdc086", "#ffff99"]);
d3.csv("data.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}, function(error, data) {
if (error) throw error;
var keys = data.columns.slice(1);
x.domain(data.map(function(d) { return d.Year; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]).nice();
color.domain(keys);
g.append("g")
.selectAll("g")
.data(d3.stack().keys(keys)(data))
.enter().append("g")
.attr("fill", function(d) { return color(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("x", function(d) { return x(d.data.Year); })
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return y(d[0]) - y(d[1]); })
.attr("width", x.bandwidth());
rect = g.selectAll("rect");
});
d3.selectAll("input")
.on("change", changed);
function changed() {
if (this.value === "step1") transitionStep1();
else if (this.value === "step2") transitionStep2();
}
function transitionStep1() {
rect.transition()
.attr("y", function(d) { return y(d[1]); })
.attr("x", function(d) { return x(d.data.Year); })
.attr("width", x.bandwidth())
.attr("stroke", "green");
}
function transitionStep2() {
rect.transition()
.attr("x", function(d) { return x(d.data.Year) + x.bandwidth() / 7 * 1; })
.attr("width", x.bandwidth() / 7)
.attr("y", function(d) { return y(d[1] - d[0]); })
.attr("stroke", "red");
}
</script></body></html>
And the csv file:
Year,A,B,C,D
1995,60,47,28,39
1996,29,56,99,0
1997,30,26,63,33
1998,37,16,48,0
1999,46,49,64,21
2000,78,88,81,57
2001,18,11,11,64
2002,91,76,79,64
2003,30,99,96,79
The example you're referring has linear values to group the chart into and so .attr("x", function(d, i) { return x(i) + x.bandwidth() / n * this.parentNode.__data__.key; }) works fine.
In your case, the columns/keys is not a linear scale but an ordinal value set that you have to set a scale for:
Refer simple d3 grouped bar chart
To do that i.e. set up a ordinal scale, here's what can be done:
var x1 = d3.scaleBand();
x1.domain(keys).rangeRound([0, x.bandwidth()]);
So this new scale would have a range of the x scale's bandwidth with the domain of ["A", "B", "C", "D"]. Using this scale to set the x attribute of the rects to group them:
.attr("x", function(d) {
return x(d.data.Year) + x1(d3.select(this.parentNode).datum().key);
})
where d3.select(this.parentNode).datum().key represent the column name.
Here's JSFIDDLE (I've used d3.csvParse to parse the data but I'm sure you'll get the point here. It's just the x attribute you need to reset.
Here's a Plunkr that uses a file.
Here's a code snippet as well:
var svg = d3.select("#bar"),
margin = {top: 20, right: 20, bottom: 20, left: 20},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.08);
var x1 = d3.scaleBand();
var y = d3.scaleLinear()
.range([height, 0]);
var color = d3.scaleOrdinal()
.range(["#7fc97f", "#beaed4", "#fdc086", "#ffff99"]);
var csv = 'Year,A,B,C,D\n1995,60,47,28,39\n1996,29,56,99,0\n1997,30,26,63,33\n1998,37,16,48,0\n1999,46,49,64,21\n2000,78,88,81,57\n2001,18,11,11,64\n2002,91,76,79,64\n2003,30,99,96,79';
var data = d3.csvParse(csv), columns = ["A", "B", "C", "D"];
data.forEach(function(d) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
});
var keys = columns;
x.domain(data.map(function(d) { return d.Year; }));
x1.domain(keys).rangeRound([0, x.bandwidth()]);
y.domain([0, d3.max(data, function(d) { return d.total; })]).nice();
color.domain(keys);
g.append("g")
.selectAll("g")
.data(d3.stack().keys(keys)(data))
.enter().append("g")
.attr("fill", function(d) { return color(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("x", function(d) { return x(d.data.Year); })
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return y(d[0]) - y(d[1]); })
.attr("width", x.bandwidth());
rect = g.selectAll("rect");
d3.selectAll("input")
.on("change", changed);
function changed() {
if (this.value === "step1") transitionStep1();
else if (this.value === "step2") transitionStep2();
}
function transitionStep1() {
rect.transition()
.attr("y", function(d) { return y(d[1]); })
.attr("x", function(d) { return x(d.data.Year); })
.attr("width", x.bandwidth())
.attr("stroke", "green");
}
function transitionStep2() {
rect.transition()
.attr("x", function(d) {
return x(d.data.Year) + x1(d3.select(this.parentNode).datum().key);
})
.attr("width", x.bandwidth() / 7)
.attr("y", function(d) { return y(d[1] - d[0]); })
.attr("stroke", "red");
}
<!DOCTYPE html>
<script src="https://d3js.org/d3.v4.min.js"></script>
<html><body>
<form>
<label><input type="radio" name="mode" style="margin-left: 10" value="step1" checked>1</label>
<label><input type="radio" name="mode" style="margin-left: 20" value="step2">2</label>
</form>
<svg id = "bar" width = "500" height = "300"></svg>
Hope something helps. :)
I updated your examples so that it works,
see https://jsfiddle.net/mc5wdL6s/84/
function transitionStep2() {
rect.transition()
.duration(5500)
.attr("x", function(d,i) {
console.log("d",d);
console.log("i",i);
return x(d.data.Year) + x.bandwidth() / m / n * i; })
.attr("width", x.bandwidth() / n)
.attr("y", function(d) { return y(d[1] - d[0]); })
.attr("height", function(d) { return y(0) - y(d[1] - d[0]); })
.attr("stroke", "red");
}
You have to pass the index of the key to the individual rectangles and use this index to multiply with the reduced bandwith. If you also use the length of the keys array (instead of 7) you are CSV column count independent. You need to put the declaration of keys variable outside the d3.csv handler.
You forgot to stroke the initial rects green.
<script>
var svg = d3.select("#bar"),
margin = {top: 20, right: 20, bottom: 20, left: 20},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.08);
var y = d3.scaleLinear()
.range([height, 0]);
var color = d3.scaleOrdinal()
.range(["#7fc97f", "#beaed4", "#fdc086", "#ffff99"]);
var keys;
d3.csv("/data.csv", function(d, i, columns) {
for (i = 1, t = 0; i < columns.length; ++i) t += d[columns[i]] = +d[columns[i]];
d.total = t;
return d;
}, function(error, data) {
if (error) throw error;
keys = data.columns.slice(1);
x.domain(data.map(function(d) { return d.Year; }));
y.domain([0, d3.max(data, function(d) { return d.total; })]).nice();
color.domain(keys);
var stackData = d3.stack().keys(keys)(data);
stackData.forEach(element => {
var keyIdx = keys.findIndex(e => e === element.key);
element.forEach(e2 => { e2.keyIdx = keyIdx; });
});
g.append("g")
.selectAll("g")
.data(stackData)
.enter().append("g")
.attr("fill", function(d) { return color(d.key); })
.selectAll("rect")
.data(function(d) { return d; })
.enter().append("rect")
.attr("x", function(d) { return x(d.data.Year); })
.attr("y", function(d) { return y(d[1]); })
.attr("height", function(d) { return y(d[0]) - y(d[1]); })
.attr("width", x.bandwidth())
.attr("stroke", "green");
rect = g.selectAll("rect");
});
d3.selectAll("input")
.on("change", changed);
function changed() {
if (this.value === "step1") transitionStep1();
else if (this.value === "step2") transitionStep2();
}
function transitionStep1() {
rect.transition()
.attr("y", function(d) { return y(d[1]); })
.attr("x", function(d) { return x(d.data.Year); })
.attr("width", x.bandwidth())
.attr("stroke", "green");
}
function transitionStep2() {
rect.transition()
.attr("x", function(d, i) { return x(d.data.Year) + x.bandwidth() / (keys.length+1) * d.keyIdx; })
.attr("width", x.bandwidth() / (keys.length+1))
.attr("y", function(d) { return y(d[1] - d[0]); })
.attr("stroke", "red");
}
</script>

update d3 chart with new data

I want to update the bar chart with new data and I looked over this question:
How to update d3.js bar chart with new data
But it is not working for me. Probably because I don't know where to put the exit().remove() functions within my code. I tried putting this line
svg.selectAll("rect").exit().remove();
below the create bars section but it just removes all of the labels. Then, if I put it right after the create labels portion it removes the chart entirely. How can I get the update button change the chart with new data?
function draw(data) {
//Width and height
var w = 250;
var h = 250;
var xScale = d3.scale.ordinal()
.domain(d3.range(data.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(data)])
.range([0, h]);
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
//Create bars
svg.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "steelblue");
//Create labels
svg.selectAll("text")
.data(data)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
};
function update() {
var data = [ 25, 22, 18, 15, 13 ];
draw(data);
}
var data = [ 21, 3, 5, 21, 15 ];
window.onload = draw(data);
With d3v3 (as I can see from your code you use this version) you should update your chart this way:
In update function set the new domain for yScale:
function update(newData) {
yScale.domain([0, d3.max(newData)]);
After that, apply new selection with selectAll("rect").data(newData), store selection in rects variable and set new value for appropriate attributes (if you do not want animation effect, remove .transition() .duration(300)):
var rects = d3.select("#chart svg")
.selectAll("rect")
.data(newData);
// enter selection
rects
.enter().append("rect");
// update selection
rects
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
Exit selection with exit method:
rects
.exit().remove();
Do the same way with text. I rewrite your code, look at the example in a hidden snippet below:
var myData = [21, 3, 5, 21, 15];
//Width and height
var w = 250;
var h = 250;
var yScale = null;
function draw(initialData) {
var xScale = d3.scale.ordinal()
.domain(d3.range(initialData.length))
.rangeRoundBands([0, w], 0.05);
yScale = d3.scale.linear()
.domain([0, d3.max(initialData)])
.range([0, h]);
//Create SVG element
var svg = d3.select("#chart")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(initialData)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", "steelblue");
svg.selectAll("text")
.data(initialData)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white");
}
function update(newData) {
yScale.domain([0, d3.max(newData)]);
var rects = d3.select("#chart svg")
.selectAll("rect")
.data(newData);
// enter selection
rects
.enter().append("rect");
// update selection
rects
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d);
})
.attr("height", function(d) {
return yScale(d);
})
// exit selection
rects
.exit().remove();
var texts = d3.select("#chart svg")
.selectAll("text")
.data(newData);
// enter selection
texts
.enter().append("rect");
// update selection
texts
.transition()
.duration(300)
.attr("y", function(d) {
return h - yScale(d) + 14;
})
.text(function(d) {
return d;
})
// exit selection
texts
.exit().remove();
}
window.onload = draw(myData);
setInterval(function() {
var data = d3.range(5).map(function() {
return parseInt(Math.random() * 20 + 1);
});
update(data);
}, 3000)
<div id="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.js"></script>

D3 transitions with multiple graphs

I'm trying to add a drop down menu that selects which measure to graph. I have 8 graphs, all graphing the same measure but by different ethnicities. Below is the code, any thoughts on what I'm doing wrong? Right now i get the error exit() is not a function.
Ok i've made some progress with the following, however it's still a little wonky. The graphs are changing but are going off the charts - the yAxis is rescaling to the max of all of the graphs, not the local one.:
function updateGraphs(newData) {
d3.selectAll("svg").each(function(d, i){
eachRace = d.values;
svg = d3.select(this);
yMax = d3.max(eachRace, function(d) { return d[newData]; });
yScale = d3.scale.linear().domain([0, yMax*1.25]).range([height/8, 0]).nice();
yAxis = d3.svg.axis().scale(yScale).orient("left").ticks(5);
line = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return yScale(d[newData]); })
d3.transition().duration(1000).selectAll(".line")
.attr("id", function(d) { return d.key ;})
.attr('class', 'line')
.attr('opacity', .8)
.attr('d', function(d) { return line(d.values); })
d3.selectAll(".y.axis")
.call(yAxis);
});
}
var svgContainer = d3.select("body").selectAll("svg")
.data(data2)
svgContainer.enter()
.append("svg")
.attr("width", 150)
.attr("height", 400)
.attr("transform", "translate(" + margin.left + "," + margin.top+ ")");
d3.selectAll("svg").each(function(d, i){
var eachRace = d.values;
var svg = d3.select(this);
var yMax = d3.max(eachRace, function(d) { return d.app; });
var yScale = d3.scale.linear().domain([0, yMax*1.25]).range([height/8, 0]).nice();
var yAxis = d3.svg.axis().scale(yScale).orient("left").ticks(5);
var line = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return yScale(d.app); })
svg.append("path")
.attr("id", function(d) { return d.key ;})
.attr('class', 'line')
.attr('opacity', .8)
.attr('d', function(d) { return line(d.values); })
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
});
Thanks JSBob for working with me. I've got it working with:
function updateGraphs(newData) {
d3.selectAll("svg").each(function(d, i){
eachRace = d.values;
svg = d3.select(this);
yMax = d3.max(eachRace, function(d) { return d[newData]; });
yScale = d3.scale.linear().domain([0, yMax*1.25]).range([height/8, 0]).nice();
yAxis = d3.svg.axis().scale(yScale).orient("left").ticks(5);
console.log(yMax);
line = d3.svg.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return yScale(d[newData]); })
svg.transition().duration(1000).select(".line")
.attr("id", function(d) { return d.key ;})
.attr('class', 'line')
.attr('opacity', .8)
.attr('d', function(d) { return line(d.values); });
svg.transition().duration(1000).select(".y.axis")
.call(yAxis);
});
}

Updating a stacked bar chart in d3.js (includes JSFiddle)

jsfiddle example can be seen here
I'm expecting the chart to update correctly with the new dataset contained in the function "redraw", however this isn't happening.
Although the current rects are updated with the new dataset, the issue seems to be that the enter().append() part of the code isn't working:
var groups = svg.selectAll('g')
.data(dataset, retd);
groups.style('fill', function (d, i) {
return colours(i);
});
groups.enter()
.append('g')
.style('fill', function (d, i) {
return colours(i);
});
groups.exit().remove();
//update the Rects
var rects = groups.selectAll('rect')
.data(function (d) {
return d;
}, thisy);
rects.transition()
.attr('x', function (d) {
return xScale(d.x0);
})
.attr('y', function (d, i) {
return yScale(d.y);
})
.attr('height', function (d) {
return yScale.rangeBand();
})
.attr('width', function (d) {
return xScale(d.x);
});
rects.enter()
.append('rect')
.attr('x', function (d) {
return xScale(d.x0);
})
.attr('y', function (d, i) {
return yScale(d.y);
})
.attr('height', function (d) {
return yScale.rangeBand();
})
.attr('width', function (d) {
return xScale(d.x);
});
Any help/insight would be appreciated.
Since the first draw worked fine, I turned it into a function. Only had to remove the already written SVG to make it reusable:
JSFiddle
<button id="reset">Redraw</button>
<script>
document.getElementById('reset').onclick = function() {
var dataset = [
{"data":[
{"IssueMonth":"Apr","IS":"350","month":"Apr"},
{"IssueMonth":null,"IS":"100","month":"Aug"},
{"IssueMonth":null,"IS":"0","month":"Dec"}],
"name":"CHF"},
{"data":[
{"IssueMonth":null,"IS":"100","month":"Apr"},
{"IssueMonth":null,"IS":"200","month":"Aug"},
{"IssueMonth":null,"IS":"40","month":"Dec"}],
"name":"GBP"}
];
drawit(dataset);
}
var dataset = [
{"data":[
{"IssueMonth":"Apr","IS":"350","month":"Apr"},
{"IssueMonth":null,"IS":"0","month":"Aug"},
{"IssueMonth":null,"IS":"0","month":"Dec"}],
"name":"CHF"},
{"data":[
{"IssueMonth":null,"IS":"100","month":"Apr"},
{"IssueMonth":null,"IS":"0","month":"Aug"},
{"IssueMonth":null,"IS":"50","month":"Dec"}],
"name":"GBP"}
];
drawit(dataset);
function drawit(dataset) {
var margins = {
top: 40,
left: 40,
right: 40,
bottom: 40
};
var width = 400;
var height = 500 - margins.top - margins.bottom;
var series = dataset.map(function (d) {
return d.name;
});
var dataset = dataset.map(function (d) {
return d.data.map(function (o, i) {
// Structure it so that your numeric
// axis (the stacked amount) is y
return {
y: +o.IS,
x: o.month
};
});
});
stack = d3.layout.stack();
stack(dataset);
var dataset = dataset.map(function (group) {
return group.map(function (d) {
// Invert the x and y values, and y0 becomes x0
return {
x: d.y,
y: d.x,
x0: d.y0
};
});
});
d3.select("svg").remove();
var svg = d3.select('body')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')')
var xMax = d3.max(dataset, function (group) {
return d3.max(group, function (d) {
return d.x + d.x0;
});
})
var xScale = d3.scale.linear()
.domain([0, xMax])
.range([0, width]);
var months = dataset[0].map(function (d) {
return d.y;
});
var yScale = d3.scale.ordinal()
.domain(months)
.rangeRoundBands([0, height], .1);
var xAxis = d3.svg.axis()
.scale(xScale)
.orient('bottom');
var yAxis = d3.svg.axis()
.scale(yScale)
.orient('left');
var colours = d3.scale.category20();
var groups = svg.selectAll('g')
.data(dataset)
.enter()
.append('g')
.style('fill', function (d, i) {
return colours(i);
});
var rects = groups.selectAll('rect')
.data(function (d) {
return d;
})
.enter()
.append('rect')
.attr('x', function (d) {
return xScale(d.x0);
})
.attr('y', function (d, i) {
return yScale(d.y);
})
.attr('height', function (d) {
return yScale.rangeBand();
})
.attr('width', function (d) {
return xScale(d.x);
});
svg.append('g')
.attr('class', 'x axis')
.attr('transform', 'translate(0,' + height + ')')
.call(xAxis);
svg.append('g')
.attr('class', 'y axis')
.call(yAxis);
}
</script>

Categories