Having trouble with updating D3.js multiline chart - javascript
I am fairly new to D3 and am hitting a problem.
I've created a simplied example of what I'm trying to achieve.
Firstly, I have a CSV file with data. In this example, it consists of phone sales data for some popular phones for several months for 2 stores. The data is shown below:
Store,Product,Month,Sold
London,iPhone,0,5
London,iPhone,1,4
London,iPhone,2,3
London,iPhone,3,5
London,iPhone,4,6
London,iPhone,5,7
London,Android Phone,0,3
London,Android Phone,1,4
London,Android Phone,2,5
London,Android Phone,3,7
London,Android Phone,4,8
London,Android Phone,5,9
London,Windows Phone,0,1
London,Windows Phone,1,2
London,Windows Phone,2,6
London,Windows Phone,3,7
London,Windows Phone,4,8
London,Windows Phone,5,5
Glasgow,iPhone,0,3
Glasgow,iPhone,1,4
Glasgow,iPhone,2,5
Glasgow,iPhone,3,2
Glasgow,iPhone,4,1
Glasgow,iPhone,5,3
Glasgow,Android Phone,0,4
Glasgow,Android Phone,1,3
Glasgow,Android Phone,2,7
Glasgow,Android Phone,3,4
Glasgow,Android Phone,4,3
Glasgow,Android Phone,5,6
Glasgow,Windows Phone,0,3
Glasgow,Windows Phone,1,6
Glasgow,Windows Phone,2,7
Glasgow,Windows Phone,3,5
Glasgow,Windows Phone,4,3
Glasgow,Windows Phone,5,4
I've written the following code in JS/D3.js:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
fill:none;
stroke:#000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke-width: 1.5px;
}
</style>
<body>
<p id="menu"><b>Test</b>
<br>Select Store:
<select>
<option value="0">London</option>
<option value="1">Glasgow</option>
</select>
</p>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 900 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// construct a linear scale for x axis
var x = d3.scale.linear()
.range([0,width]);
// construct a linear scale for y axis
var y = d3.scale.linear()
.range([height,0]);
// use the default line colours (see http://stackoverflow.com/questions/21208031/how-to-customize-the-color-scale-in-a-d3-line-chart for info on setting colours per line)
var color = d3.scale.category10();
// create the x axis and orient of ticks and labels at the bottom
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// create the y axis and orient of ticks and labels on the left
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// line generator function
var line = d3.svg.line()
//.interpolate("basis")
.x(function(d) { return x(d.Month); })
.y(function(d) { return y(d.Sold); });
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
d3.csv("sampleData.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key == "Product"; }));
// first we need to corerce the data into the right formats
// map the data from the CSV file
data = data.map( function (d) {
return {
Store: d.Store,
Product: d.Product,
Month: +d.Month,
Sold: +d.Sold };
});
// nest the data by regime and then CI
var salesDataByStoreProduct = d3.nest()
.key(function(d) { return d.Store; })
.key(function(d) { return d.Product; })
.entries(data);
// get the first regime's nest
var salesDataForLondon;
salesDataForLondon = salesDataByStoreProduct[0].values;
console.log(salesDataForLondon);
x.domain([d3.min(salesDataForLondon, function(d) { return d3.min(d.values, function (d) { return d.Month; }); }),
d3.max(salesDataForLondon, function(d) { return d3.max(d.values, function (d) { return d.Month; }); })]);
y.domain([0, d3.max(salesDataForLondon, function(d) { return d3.max(d.values, function (d) { return d.Sold; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var Products = svg.selectAll(".Product")
.data(salesDataForLondon, function(d) { return d.key; })
.enter().append("g")
.attr("class", "Product");
Products.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.key); });
function redraw()
{
var salesDataByStoreProduct = d3.nest()
.key(function(d) { return d.Store; })
.key(function(d) { return d.Product; })
.entries(data);
var salesDataForGlasgow;
salesDataForGlasgow = salesDataByStoreProduct[1].values;
console.log(salesDataForGlasgow);
x.domain([d3.min(salesDataForGlasgow, function(d) { return d3.min(d.values, function (d) { return d.Product; }); }),
d3.max(salesDataForGlasgow, function(d) { return d3.max(d.values, function (d) { return d.Product; }); })]);
y.domain([0, d3.max(salesDataForGlasgow, function(d) { return d3.max(d.values, function (d) { return d.Sales; }); })]);
svg.select("g")
.call(xAxis);
svg.select("g")
.call(yAxis);
var Products = svg.selectAll(".Product")
.data(salesDataForGlasgow, function(d) { return d.key; })
.enter().select("g")
.attr("class", "Product");
Products.select("path")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.key); });
}
/******************************************************/
var menu = d3.select("#menu select")
.on("change", change);
function change()
{
clearTimeout(timeout);
d3.transition()
.duration(altKey ? 7500 : 1500);
redraw();
}
var timeout = setTimeout(function() {
menu.property("value", "ENEUSE").node().focus();
change();
}, 7000);
var altKey;
d3.select(window)
.on("keydown", function() { altKey = d3.event.altKey; })
.on("keyup", function() { altKey = false; });
/******************************************************/
});
</script>
</body>
</html>
where I've read in the CSV file and then used D3 nests to create a hierarchy as shown below:
Store->Product->Month->Sales
I want the chart to present the sales data per product by month for London and then if the selection is changed, to show the sales data by month for Glasgow.
However, although the London data is being presented, the chart isn't being updated when I select Glasgow.
To rule out anything too obvious, I've hardcoded the array index for each store.
I've also added console.log and can see the right data is being used but just not rendered in the chart when redraw() is being called.
I'd be grateful of any suggestions of the cause of the problem which I suspect it related to the following code:
var Products = svg.selectAll(".Product")
.data(salesDataForGlasgow, function(d) { return d.key; })
.enter().select("g")
.attr("class", "Product");
Products.select("path")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.key); });
Any other advice on improving or simplifying the code would be very gratefully appreciated.
As you suspect, the problem is indeed in these two statements:
var Products = svg.selectAll(".Product")
.data(salesDataForGlasgow, function(d) { return d.key; })
.enter().select("g")
.attr("class", "Product");
Products.select("path")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.key); });
Products is derived from the .enter() selection. This contains one element for each data item that isn't joined to an existing element in the DOM. When changing the graph to show the Glasgow data, there are no new elements to add (the London data has three products as does the Glasgow data), so the .enter() selection is empty.
Instead, you need to restart the selection from .Product. Change the second of the two statements to the following:
svg.selectAll(".Product")
.select("path")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.key); });
There are some other issues I found in your code. Firstly, the three lines that set x.domain() and y.domain() use the wrong property names at the end. This causes various NaNs to appear in the ranges of the x and y scales as D3 attempts to convert product names or undefined to numbers. At the end of these three lines, replace d.Product with d.Month and d.Sales with d.Sold, so that they are consistent with the lines that set the ranges of the x and y scales for the London sales data.
Finally, you need to adjust how you reset the axes. At the moment you are using the following code:
svg.select("g")
.call(xAxis);
svg.select("g")
.call(yAxis);
This ends calling the xAxis and then yAxis functions on all g elements, including both axes, all axis ticks and the three graph lines, so the graph looks a bit confused. You've set the class of the X-axis to x axis, but because class names can't have spaces in you've actually given the axis the classes x and axis. A similar thing happens with the y-axis.
What you need to do is to select the axes individually, using the classes you've assigned to them, before calling xAxis or yAxis. Replace the lines above with the following:
svg.select("g.x.axis")
.call(xAxis);
svg.select("g.y.axis")
.call(yAxis);
After you've made all these changes the graph should hopefully do what you want.
While this isn't a code review site, your code could take significant refactoring. First, you aren't handling the enter, update, exit pattern correctly. Second, once you handle the pattern correctly you don't need a seperate redraw function. Just one function to handle creation and update.
Here's a quick refactor:
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.x.axis path {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke-width: 1.5px;
}
</style>
<body>
<p id="menu"><b>Test</b>
<br>Select Store:
<select>
<option value="London">London</option>
<option value="Glasgow">Glasgow</option>
</select>
</p>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var margin = {
top: 20,
right: 80,
bottom: 30,
left: 50
},
width = 900 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
// construct a linear scale for x axis
var x = d3.scale.linear()
.range([0, width]);
// construct a linear scale for y axis
var y = d3.scale.linear()
.range([height, 0]);
// use the default line colours (see http://stackoverflow.com/questions/21208031/how-to-customize-the-color-scale-in-a-d3-line-chart for info on setting colours per line)
var color = d3.scale.category10();
// create the x axis and orient of ticks and labels at the bottom
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
// create the y axis and orient of ticks and labels on the left
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
// line generator function
var line = d3.svg.line()
//.interpolate("basis")
.x(function(d) {
return x(d.Month);
})
.y(function(d) {
return y(d.Sold);
});
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
// create gs for axis but don't add yet
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")");
svg.append("g")
.attr("class", "y axis");
var salesDataByStoreProduct = null;
d3.csv("data.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) {
return key == "Product";
}));
// first we need to corerce the data into the right formats
// map the data from the CSV file
data = data.map(function(d) {
return {
Store: d.Store,
Product: d.Product,
Month: +d.Month,
Sold: +d.Sold
};
});
// nest the data by regime and then CI
salesDataByStoreProduct = d3.nest()
.key(function(d) {
return d.Store;
})
.key(function(d) {
return d.Product;
})
.entries(data);
draw("London");
});
function draw(which) {
// get the first regime's nest
var salesData = null;
salesDataByStoreProduct.forEach(function(d) {
if (d.key === which) {
salesData = d.values;
}
});
// set domains
x.domain([d3.min(salesData, function(d) {
return d3.min(d.values, function(d) {
return d.Month;
});
}),
d3.max(salesData, function(d) {
return d3.max(d.values, function(d) {
return d.Month;
});
})
]);
y.domain([0, d3.max(salesData, function(d) {
return d3.max(d.values, function(d) {
return d.Sold;
});
})]);
// draw axis
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
// this is the update selection
var Products = svg.selectAll(".Product")
.data(salesData, function(d) {
return d.key;
});
// this is the enter selection
Products
.enter().append("g")
.attr("class", "Product")
.append("path");
// now do update
Products.selectAll("path")
.attr("class", "line")
.attr("d", function(d) {
return line(d.values);
})
.style("stroke", function(d) {
return color(d.key);
});
}
var menu = d3.select("#menu select")
.on("change", change);
function change() {
draw(this.options[this.selectedIndex].value);
}
</script>
</body>
</html>
Running code here.
Related
D3 line chart data not aligned proper on x axis [duplicate]
My data points and the values in the scaleBand y axis are not aligned. I am not able to align them properly, when I read the documentation, saw that by default the alignment is 0.5 and that's why my data points are plotted between the two points in the axis. But I tried to override the alignment my giving the alignment as 0, but there seems to be no change. The following is my code. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge"/> <title>D3 v4 - linechart</title> <style> #graph { width: 900px; height: 500px; } .tick line { stroke-dasharray: 2 2 ; stroke: #ccc; } .y path{ fill: none; stroke: none; } </style> </head> <body> <div id="graph"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.1.1/d3.min.js"></script> <script> !(function(){ "use strict" var width,height var chartWidth, chartHeight var margin var svg = d3.select("#graph").append("svg") var axisLayer = svg.append("g").classed("axisLayer", true) var chartLayer = svg.append("g").classed("chartLayer", true) var xScale = d3.scaleLinear() var yScale = d3.scaleBand() var align = 0 //d3.tsv("data1.tsv", cast, main) d3.json("http://localhost/d32.json",cast) //データの方変換 function cast(data) { console.log("got it"); data.forEach(function(data) { console.log(data.Letter); data.Letter = data.Letter; data.Freq = +data.Freq; }); main(data); } function main(data) { console.log("in main"); setSize(data) drawAxis() drawChart(data) } function setSize(data) { width = document.querySelector("#graph").clientWidth height = document.querySelector("#graph").clientHeight margin = {top:40, left:100, bottom:40, right:0 } chartWidth = width - (margin.left+margin.right+8) chartHeight = height - (margin.top+margin.bottom) svg.attr("width", width).attr("height", height) axisLayer.attr("width", width).attr("height", height) chartLayer .attr("width", chartWidth) .attr("height", chartHeight) .attr("transform", "translate("+[margin.left, margin.top]+")") xScale.domain([0, d3.max(data, function(d) { return d.Freq; })]).range([0,chartWidth]) yScale.domain(data.map(function(d) { return d.Letter; })).range([chartHeight, 0]).align(1) } function drawChart(data) { console.log("in drawChart"); var t = d3.transition() .duration(8000) .ease(d3.easeLinear) .on("start", function(d){ console.log("transiton start") }) .on("end", function(d){ console.log("transiton end") }) var lineGen = d3.line() .x(function(d) { return xScale(d.Freq) }) .y(function(d) { return yScale(d.Letter) }) .curve(d3.curveStepAfter) var line = chartLayer.selectAll(".line") .data([data]) line.enter().append("path").classed("line", true) .merge(line) .attr("d", lineGen) .attr("fill", "none") .attr("stroke", "blue") .attr("stroke-width","2px") .attr("stroke-dasharray", function(d){ return this.getTotalLength() }) .attr("stroke-dashoffset", function(d){ return this.getTotalLength() }) chartLayer.selectAll(".line").transition(t) .attr("stroke-dashoffset", 0) chartLayer.selectAll("circle").classed("circle",true) .data(data) .enter().append("circle") .attr("class", "circle") .attr("fill","none") .attr("stroke","black") .attr("cx", function(d) { return xScale(d.Freq); }) .attr("cy", function(d) { return yScale(d.Letter); }) .attr("r", 4); chartLayer.selectAll(".logo").transition(t) .attr("stroke-dashoffset", 0) } function drawAxis(){ var yAxis = d3.axisLeft(yScale) .tickSizeInner(-chartWidth) axisLayer.append("g") .attr("transform", "translate("+[margin.left, margin.top]+")") .attr("class", "axis y") .call(yAxis); var xAxis = d3.axisBottom(xScale) axisLayer.append("g") .attr("class", "axis x") .attr("transform", "translate("+[margin.left, chartHeight+margin.top]+")") .call(xAxis); } }()); </script> </body> </html> The output is shown here:
The band scale is the wrong tool in this situation. The main reason is that a band scale has an associated bandwidth. You can tweak the paddingInner and paddingOuter values of the band scale to give you the expected result. However, the easiest solution is using a point scale instead. Point scales: ...are a variant of band scales with the bandwidth fixed to zero. (emphasis mine) So, it should be: var yScale = d3.scalePoint()
d3js multigraph auto update
I could really use some help fixing a d3js related problem.. I did everything I know and googled everywhere but still can’t figure out the solution. I’ve got a simple database as shown below. when executing the code it reads all the data and everything is fine, when it’s doing it’s refresh it’s updating the temperature graph but not the humidity... I tried many things including adding valueline2 to the update function but it still doesn't work... Any help would be much appreciated thanks. dtg | temperature | hum 2016-03-02 09:14:00 23 40 2016-03-02 09:10:00 22 45 <!DOCTYPE html> <meta charset="utf-8"> <style> /* set the CSS */ body { font: 14px Arial;} path { stroke: steelblue; stroke-width: 2; fill: none; } .axis path, .axis line { fill: none; stroke: grey; stroke-width: 1; shape-rendering: crispEdges; } /* Addon 5,6,7 - part 1*/ .grid .tick { stroke: lightgrey; stroke-opacity: 0.7; shape-rendering: crispEdges; } .grid path { stroke-width: 0; } </style> <body> <!-- load the d3.js library --> <script src="http://d3js.org/d3.v3.min.js"></script> <script> // Set the dimensions of the canvas / graph var margin = {top: 30, right: 60, bottom: 50, left: 50}, width = 600 - margin.left - margin.right, height = 300 - margin.top - margin.bottom; // Parse the date / time /* var parseDate = d3.time.format("%d-%b-%y").parse; */ var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse; // Set the ranges var x = d3.time.scale().range([0, width]); var y = d3.scale.linear().range([height, 0]); // Define the axes var xAxis = d3.svg.axis().scale(x) .orient("bottom").ticks(6); var yAxis = d3.svg.axis().scale(y) .orient("left").ticks(8); // Define the line var valueline = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.dtg); }) .y(function(d) { return y(d.temperature); }); // Define the 2nd line -- Addon 9 part 1 var valueline2 = d3.svg.line() .interpolate("basis") .x(function(d) { return x(d.dtg); }) .y(function(d) { return y(d.hum); }); // Adds the svg canvas var svg = d3.select("body") .append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Addon 5,6,7 - part 2 function make_x_axis() { return d3.svg.axis() .scale(x) .orient("bottom") .ticks(8) } function make_y_axis() { return d3.svg.axis() .scale(y) .orient("left") .ticks(8) } // Get the data d3.json("data.php", function(error, data) { data.forEach(function(d) { d.dtg = parseDate(d.dtg); d.temperature = +d.temperature; d.hum = +d.hum; // Addon 9 part 3 }); // Scale the range of the data x.domain(d3.extent(data, function(d) { return d.dtg; })); y.domain([0, d3.max(data, function(d) { return Math.max(d.temperature, d.hum)+5; })]); // y.domain([0, d3.max(data, function(d) { return d.temperature; })]); // Add the valueline path. svg.append("path") .attr("class", "line") .attr("d", valueline(data)); // Add the valueline2 path - Addon 9 part 2 svg.append("path") .attr("class", "line") .style("stroke", "red") .attr("d", valueline2(data)); // Add the X Axis svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); // Add the Y Axis svg.append("g") .attr("class", "y axis") .call(yAxis); // Addon 4 svg.append("g") // Add the Y Axis .attr("class", "y axis") .call(yAxis); // Addon 5,6,7 - part 3 svg.append("g") .attr("class", "grid") .attr("transform", "translate(0," + height + ")") .call(make_x_axis() .tickSize(-height, 0, 0) .tickFormat("") ) svg.append("g") .attr("class", "grid") .call(make_y_axis() .tickSize(-width, 0, 0) .tickFormat("") ) }); var inter = setInterval(function() { updateData(); }, 5000); // ** Update data section (Called from the onclick) function updateData() { // Get the data again d3.json("data.php", function(error, data) { data.forEach(function(d) { d.dtg = parseDate(d.dtg); d.temperature = +d.temperature; d.hum = +d.hum; }); // Scale the range of the data again x.domain(d3.extent(data, function(d) { return d.dtg; })); y.domain([0, d3.max(data, function(d) { return Math.max(d.temperature, d.hum) + 5; })]); // Addon 9 part 4 // Select the section we want to apply our changes to var svg = d3.select("body").transition(); // Make the changes svg.select(".line").duration(750).attr("d", valueline(data)); svg.select("x.axis").duration(750).call(xAxis); svg.select("y.axis").duration(750).call(yAxis); }); } </script> </body>
You need to give different names to your different lines. Right now both lines only have the same class: ".line". // Add the valueline path. svg.append("path") .attr("class", "line") .attr("id", "line1") //new id .attr("d", valueline(data)); // Add the valueline2 path - Addon 9 part 2 svg.append("path") .attr("class", "line") .attr("id", "line2") //new id .style("stroke", "red") .attr("d", valueline2(data)); Then in the update, you need to actually update both lines: // Make the changes svg.select("#line1").duration(750).attr("d", valueline(data)); //update line 1 svg.select("#line2").duration(750).attr("d", valueline2(data)); //update line 2 svg.select("x.axis").duration(750).call(xAxis); svg.select("y.axis").duration(750).call(yAxis); Another more "D3-friendly" approach would be to give the temperature data to your first path, the humidity data to the second one, and then call a variant of valueline on each path, each one with their respective data.
Issue with D3 multi-line chart
Hello I am trying to build a multi-line chart that displays rates for each month year over year. I am getting a "TypeError: t is undefined" error in the console and while I can see the x and y axis populated, no lines are appearing in the chart. Any help appreciated! The HTML file code is here: <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } .x.axis path { display: none; } .line { fill: none; stroke: steelblue; stroke-width: 1.5px; } </style> <body> <script src="//d3js.org/d3.v3.min.js"></script> <script> var margin = {top: 20, right: 80, bottom: 30, left: 50}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.scale.ordinal().rangeRoundBands([0, width], .1); var y = d3.scale.linear().range([height, 0]); var color = d3.scale.ordinal().range(["#666666", "#262626", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]); var xAxis = d3.svg.axis().scale(x).orient("bottom"); var yAxis = d3.svg.axis().scale(y).orient("left"); var line = d3.svg.line().interpolate("basis").x(function(d) { return x(d.date); }).y(function(d) { return y(d.value); }); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.json("yoy_values.json", function(error, data) { if (error) throw error; var myValues = d3.keys(data[0]).filter(function(key) { return key !== "date"; }); data.forEach(function(d) { d.rates = myValues.map(function(name) { return {name: name, value: +d[name]}; }); console.log(d.rates); }); x.domain(data.map(function(d) { return d.date; })); y.domain([ d3.min(data, function(d) { return d3.min(d.rates, function(d) { return d.value; }); }), d3.max(data, function(d) { return d3.max(d.rates, function(d) { return d.value; }); }) ]); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .call(yAxis) .append("text") .attr("transform", "rotate(-90)") .attr("y", 6) .attr("dy", ".71em") .style("text-anchor", "end") .text("Rates"); var state = svg.selectAll(".state") .data(myValues.slice().reverse()) .enter().append("g") .attr("class", "state") .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; }); state.append("path") .attr("class", "line") .attr("d", function(d) { return line(d.rates); }) .style("stroke", function(d) { return color(d.name); }); state.append("text") .datum(function(d) { return {name: d.name, value: d.rates[d.rates.length - 1]}; }) .attr("transform", function(d) { return "translate(" + x(d.value) + "," + y(d.name) + ")"; }) .attr("x", 3) .attr("dy", ".35em") .text(function(d) { return d.name; }); }); </script> The JSON file I am reading looks like this: [ {"date":"Jan","2014":"0.0812","2015":"0.0780","2016":"0.0838"}, {"date":"Feb","2014":"0.0806","2015":"0.0768","2016":"0.0893"}, {"date":"Mar","2014":"0.0858","2015":"0.0847","2016":null}, {"date":"Apr","2014":"0.0848","2015":"0.0889","2016":null}, {"date":"May","2014":"0.0890","2015":"0.0890","2016":null}, {"date":"Jun","2014":"0.0928","2015":"0.0865","2016":null}, {"date":"Jul","2014":"0.0857","2015":"0.0799","2016":null}, {"date":"Aug","2014":"0.0905","2015":"0.0845","2016":null}, {"date":"Sep","2014":"0.1003","2015":"0.0934","2016":null}, {"date":"Oct","2014":"0.0971","2015":"0.0993","2016":null}, {"date":"Nov","2014":"0.0912","2015":"0.0973","2016":null}, {"date":"Dec","2014":"0.0800","2015":"0.0777","2016":null} ]
It's hard to tell from just code eyeballing, but I noticed: You make a series of .rates properties from the non-"date" json data, so .rates for the first datum would be [{name:"2014", value:"0.0812"},{name:"2015", value:"0.0780"},{name:"2016", value:"0.0838"}] d.rates = myValues.map(function(name) { return {name: name, value: +d[name]}; }); You then pass these to a d3.svg.line function .attr("d", function(d) { return line(d.rates); }) But this line function has been previously set up to seemingly expect .date and .value properties not .name and .value var line = d3.svg.line().interpolate("basis").x(function(d) { return x(d.date); }).y(function(d) { return y(d.value); }); And the scale x has been set up to expect .date (the month strings) as arguments, because they were set as the domain x.domain(data.map(function(d) { return d.date; })); In short, it seems the x scale and line function are expecting data objects categorised by month to draw one line per year, but you're passing in the .rates objects which are organised by year in the expectation of drawing one line per month?
Ideas for distinct layering of stacked graph in D3.js
i have data for the first and following attempt of seeking asylum in germany for refugees and therefore two graphs which are looking like this First one Second one Transition from one to another shoulnd't be a problem i suppose but what I want is so show both of them in one graph too. So a combination of both datasets for each country. But is it possible to distinguish from one another if I combine countries and the first and following ("erst/folge")? Each country should have on layer divided by two, one is the first attempt the other is the second attempt of this country. One idea to differ those sub-layers is maybe custom coloscale which I try right now. How can I show both data in one graph? Is it even possible to join both datasets and still see the difference? Here is my html: <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; } .chart { background: #fff; } p { font: 12px helvetica; } .axis path, .axis line { fill: none; stroke: #000; stroke-width: 2px; shape-rendering: crispEdges; } button { position: absolute; right: 50px; top: 10px; } </style> <body> <script src="http://d3js.org/d3.v2.js"></script> <div id="option"> <input name="updateButton" type="button" value="Show Data for second Attemp" onclick="updateSecond('folgeantraege_monatlich_2015_mitentscheidungenbisnovember.csv')" /> </div> <div id="option"> <input name="updateButton" type="button" value="Show Data for first Attemp" onclick="updateFirst('erstantraege_monatlich_2015_mitentscheidungenbisnovember.csv')" /> </div> <div id="option"> <input name="updateButton" type="button" value="Show both" onclick="updateBoth('erstantraege_monatlich_2015_mitentscheidungenbisnovember.csv', 'folgeantraege_monatlich_2015_mitentscheidungenbisnovember.csv')" /> </div> <div class="chart"> </div> <script> var margin = {top: 20, right: 40, bottom: 30, left: 30}; var width = document.body.clientWidth - margin.left - margin.right; var height = 400 - margin.top - margin.bottom; var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height-10, 0]); var dateParser = d3.time.format("%Y-%m-%d").parse; var stack = d3.layout.stack() .offset("zero") .values(function(d) { return d.values; }) .x(function(d) { return d.date; }) .y(function(d) { return d.value; }); var area = d3.svg.area() .interpolate("cardinal") .x(function(d) { return x(d.date); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }); var z = d3.scale.category20() chart("erstantraege_monatlich_2015_mitentscheidungenbisnovember.csv"); var datearray = []; var colorrange = []; function chart(csvpath) { // var dateParser = d3.time.format("%Y-%m-%d").parse; // var margin = {top: 20, right: 40, bottom: 30, left: 30}; // var width = document.body.clientWidth - margin.left - margin.right; // var height = 400 - margin.top - margin.bottom; // var x = d3.time.scale() // .range([0, width]); // // var y = d3.scale.linear() // .range([height-10, 0]); // var z = d3.scale.category20() //var color = d3.scale.category10() var xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(d3.time.months); var yAxis = d3.svg.axis() .scale(y); var yAxisr = d3.svg.axis() .scale(y); // var stack = d3.layout.stack() // .offset("zero") // .values(function(d) { return d.values; }) // .x(function(d) { return d.date; }) // .y(function(d) { return d.value; }); var nest = d3.nest() .key(function(d) { return d.Land}); // var nestFiltered = nest.filter(function(d){ // return d.Land != 'Total'; // }) // var area = d3.svg.area() // .interpolate("cardinal") // .x(function(d) { return x(d.date); }) // .y0(function(d) { return y(d.y0); }) // .y1(function(d) { return y(d.y0 + d.y); }); var svg = d3.select(".chart").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.csv(csvpath, function(data) { data.forEach(function(d) { d.date = dateParser(d.Datum); d.value = +d.ErstanträgeZahl; }); //onsole.log(data); var layers = stack(nest.entries(data)); console.log(nest.entries(data)); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]); svg.selectAll(".layer") .data(layers) .enter().append("path") .attr("class", "layer") .attr("d", function(d) { return area(d.values); }) .style("fill", function(d, i) { return z(i); }); svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); svg.append("g") .attr("class", "y axis") .attr("transform", "translate(" + width + ", 0)") .call(yAxis.orient("right")); svg.append("g") .attr("class", "y axis") .call(yAxis.orient("left")); }); } function updateSecond(csvpath) { var nest = d3.nest() .key(function(d) { return d.Land}); d3.csv(csvpath, function(data) { data.forEach(function(d) { d.date = dateParser(d.Datum); d.value = +d.Summe; console.log(d.date); console.log(d.value); }); var layers = stack(nest.entries(data)); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]); d3.selectAll("path") .data(layers) .transition() .duration(750) .style("fill", function(d, i) { return z(i); }) .attr("d", function(d) { return area(d.values); }); svg.select(".y.axis") // change the y axis .duration(750) .call(yAxis); }); } function updateFirst(csvpath) { var nest = d3.nest() .key(function(d) { return d.Land}); d3.csv(csvpath, function(data) { data.forEach(function(d) { d.date = dateParser(d.Datum); d.value = +d.ErstanträgeZahl; console.log(d.date); console.log(d.value); }); var layers = stack(nest.entries(data)); x.domain(d3.extent(data, function(d) { return d.date; })); y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]); d3.selectAll("path") .data(layers) .transition() .duration(750) .style("fill", function(d, i) { return z(i); }) .attr("d", function(d) { return area(d.values); }); svg.select(".y.axis") // change the y axis .duration(750) .call(yAxis); }); } function updateBoth(csvpathFirst, csvpathSecond){ var nest = d3.nest() .key(function(d) { return d.Land}); d3.csv(csvpathFirst, function(data1) { d3.csv(csvpathSecond, function(data2) { }); }); } </script> And my data is here at my repo EDIT1: For example csv1 contains Datum,Land,Summe,Position,Antragsart,EntscheidungenInsgesamt,Asylberechtigt,Flüchtling,GewährungVonSubsidiäremSchutz,Abschiebungsverbot,UnbegrenzteAblehnungen,Ablehnung,sonstigeVerfahrenserledigungen 2015-01-01,Afghanistan,1129,5,Erst,418,0,105,4,58,66,6,179 2015-02-01,Afghanistan,969,5,Erst,849,9,186,16,100,131,10,397 2015-03-01,Afghanistan,885,5,Erst,1376,17,309,58,158,201,11,622 2015-04-01,Afghanistan,1119,6,Erst,1838,21,384,75,202,261,15,880 2015-05-01,Afghanistan,1151,6,Erst,2272,21,499,91,249,303,16,1093 2015-06-01,Afghanistan,2051,6,Erst,2911,23,683,132,313,377,19,1364 2015-07-01,Afghanistan,2104,6,Erst,3340,27,767,160,366,431,21,1568 2015-08-01,Afghanistan,2270,5,Erst,3660,28,922,172,409,453,23,1653 2015-09-01,Afghanistan,2724,4,Erst,4057,36,1049,201,455,475,26,1815 2015-10-01,Afghanistan,3770,4,Erst,4540,37,1188,234,516,538,29,1998 2015-11-01,Afghanistan,4929,0,Erst,5026,46,1340,253,620,623,49,2095 And csv2 contains Datum,Antragsart,Land,Summe,Position,Datum2,Position,Herkunft,Entscheidungeninsgesamt,Asylberechtigt,Prozent,Flüchtling,Pronzent,GewährungvonsubisdiäremSchutz,Prozent,Abschiebungsverbot,Prozent,UnbegrenzteAblehnungen,Prozent,Ablehnung,Prozent,keinweiteresverfahren,Prozent,sonstigeVerfahrenserledigungen,Prozent 2015-01-01,Folge,Afghanistan,33,10,2015-01-01,10,Afghanistan,29,0,0,5,17.2,2,6.9,8,27.6,0,0,0,0,1,3.4,13,44.8 2015-02-01,Folge,Afghanistan,29,10,2015-02-01,10,Afghanistan,81,0,0,13,16,4,4.9,22,27.2,0,0,0,0,10,12.3,32,39.5 2015-03-01,Folge,Afghanistan,41,9,2015-03-01,9,Afghanistan,135,0,0,21,15.6,10,7.4,37,27.4,1,0.7,0,0,23,17,43,31.9 2015-04-01,Folge,Afghanistan,25,10,2015-04-01,10,Afghanistan,165,0,0,34,20.6,12,7.3,41,24.8,4,2.4,0,0,30,18.2,44,26.7 2015-05-01,Folge,Afghanistan,37,9,2015-05-01,9,Afghanistan,212,0,0,54,25.5,12,5.7,50,23.6,4,1.9,0,0,32,15.1,60,28.3 2015-06-01,Folge,Afghanistan,35,9,2015-06-01,9,Afghanistan,261,0,0,72,27.6,17,6.5,59,22.6,6,2.3,0,0,35,13.4,72,27.6 2015-07-01,Folge,Afghanistan,35,9,2015-07-01,9,Afghanistan,288,0,0,82,28.5,17,5.9,64,22.2,6,2.1,0,0,42,14.6,77,26.7 2015-08-01,Folge,Afghanistan,34,9,2015-08-01,9,Afghanistan,321,0,0,100,31.2,20,6.2,66,20.6,6,1.9,0,0,52,16.2,77,24 2015-09-01,Folge,Afghanistan,27,4,2015-09-01,9,Afghanistan,354,0,0,120,33.9,20,5.6,72,20.3,7,2,0,0,54,15.3,81,22.9 2015-10-01,Folge,Afghanistan,24,9,2015-10-01,9,Afghanistan,389,0,0,136,35,20,5.1,83,21.3,7,1.8,0,0,54,13.9,89,22.9 2015-11-01,Folge,Afghanistan,47,,,,,431,1,0.2,148,34.3,23,5.3,97,22.5,8,1.9,0,0,58,13.5,96,22.3 The values ("Summe") should sum up the values per month of each country (Afghanistan) but also should reflect the values for their stacks on their own (Right now I'm trying to figur out how to use texture.js and custom scales to use textures to distinguish the colors from another because every country should have it's own color in this graph but as I already mentioned they should be different in their sublayers When I try to put both csv fiels in one file I get not exactly but something similar to this Can you give me some tips how to archive sub-layers (data structure/algorithm or what i takes to achieve this) so I can proceed and try to implement textures? Thanks in advance Final EDIT as answer to Cyrils : var margin = {top: 20, right: 40, bottom: 30, left: 30}; var width = document.body.clientWidth - margin.left - margin.right; var height = 400 - margin.top - margin.bottom; var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height-10, 0]); var dateParser = d3.time.format("%Y-%m-%d").parse; var stack = d3.layout.stack() .offset("zero") .values(function(d) { return d.values; }) .x(function(d) { return d.graphDate; }) .y(function(d) { return d.value; }); var area = d3.svg.area() .interpolate("cardinal") .x(function(d) { return x(d.graphDate); }) .y0(function(d) { return y(d.y0); }) .y1(function(d) { return y(d.y0 + d.y); }); var z = d3.scale.category20() doInit(); updateFirst('data/all.csv'); function doInit(){ //make the svg and axis xAxis = d3.svg.axis() .scale(x) .orient("bottom") .ticks(d3.time.months); yAxis = d3.svg.axis() .scale(y); yAxisr = d3.svg.axis() .scale(y); //make svg var graph = d3.select(".chart").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); graph.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); graph.append("g") .attr("class", "y axis yright") .attr("transform", "translate(" + width + ", 0)") .call(yAxis.orient("right")); graph.append("g") .attr("class", "y axis yleft") .call(yAxis.orient("left")); } function updateFirst(csvpath) { var nest = d3.nest() .key(function(d) { return d.Land+ "-" + d.Antragsart}); //console.log(nest); d3.csv(csvpath, function(data) { data.forEach(function(d) { //console.log(data); d.graphDate = dateParser(d.Datum); d.value = +d.Summe; d.type= d.Antragsart; }); var layers = stack(nest.entries(data)).sort(function(a,b){return d3.ascending(a.key, b.key)}); console.log(layers); x.domain(d3.extent(data, function(d) { return d.graphDate; })); y.domain([0, d3.max(data, function(d) { return d.y0 + d.y; })]); var k = d3.select("g .x") .call(xAxis); d3.select("g .yright") .call(yAxis); d3.select("g .yleft") .call(yAxis); d3.selectAll("defs").remove(); d3.select(".chart svg g").selectAll("path").remove(); d3.select(".chart svg g").selectAll("path") .data(layers).enter().append("path") //.style("fill", function(d, i) { console.log(d.key);return z(d.key); }) .attr("class", function(d){ var country = d.key.split("-")[0]; var src = d.key.split("-")[1]; return src; }) .style("fill", function(d){ var country = d.key.split("-")[0]; var src = d.key.split("-")[1]; if (src === "Folge"){ var t = textures.lines().thicker(2).stroke(z(country)); d3.select(".chart").select("svg").call(t); return t.url(); } else { return z(country); } }) .attr("d", function(d) { return area(d.values); }); }); }
For merging the records I am making use of d3 queue..Read here The purpose of this is to load 2 CSV via ajax and when both loaded calls the callback. queue() .defer(d3.csv, csvpathFirst) //using queue so that callback is called after loading both CSVs .defer(d3.csv, csvpathSecond) .await(makeMyChart); function makeMyChart(error, first, second) { var data = []; Make the nested function based on country and csv var nest = d3.nest() .key(function(d) { return d.Land + "-" + d.src; //d.src is first if first csv second if vice versa }); Next I am merging the records like this: //iterate first first.forEach(function(d) { d.graphDate = dateParser(d.Datum); d.value = +d.Summe; d.src = "first" data.push(d) }); //iterate second second.forEach(function(d) { d.graphDate = dateParser(d.Datum); d.value = +d.Summe; d.src = "second" data.push(d) }); //sort layers on basis of country var layers = stack(nest.entries(data)).sort(function(a, b) { return d3.ascending(a.key, b.key) }); Regenerate the axis like this: //regenerate the axis with new domains var k = d3.select("g .x") .call(xAxis); d3.select("g .yright") .call(yAxis); d3.select("g .yleft") .call(yAxis); Remove all old paths and defs DOM like this: d3.selectAll("defs").remove(); d3.select(".chart svg g").selectAll("path").remove(); Next based on country and first csv and second csv add style fill. .style("fill", function(d) { var country = d.key.split("-")[0]; var src = d.key.split("-")[1]; if (src === "first") { //use texture.js for pattern var t = textures.lines().thicker().stroke(z(country)); d3.select(".chart").select("svg").call(t); return t.url(); } else { return z(country); } }) Working code here Hope this helps!
How to modify color stroke in multiple charts with d3js nest() data
I'm trying to add line color condition by axis value attr("stroke","red") if date > 'Jan 2008' I have tried to modify var line with this code below, but it didn't work. Any recommendation would be appreciated. > var line = d3.svg.line() > .x(function(d) { return x(d.date); }) > .y(function(d) { return y(d.price); }) > .attr( "stroke", function(d) { if (d.date > 'Jan 2008' { return "red"}; }) from d3 code below or fullcode and dataset from this link : http://bl.ocks.org/mbostock/1157787 <!DOCTYPE html> <meta charset="utf-8"> <style> body { font: 10px sans-serif; margin: 0; } .line { fill: none; stroke: #666; stroke-width: 1.5px; } .area { fill: #e7e7e7; } </style> <body> <script src="http://d3js.org/d3.v3.min.js"></script> <script> var margin = {top: 8, right: 10, bottom: 2, left: 10}, width = 960 - margin.left - margin.right, height = 69 - margin.top - margin.bottom; var parseDate = d3.time.format("%b %Y").parse; var x = d3.time.scale() .range([0, width]); var y = d3.scale.linear() .range([height, 0]); var area = d3.svg.area() .x(function(d) { return x(d.date); }) .y0(height) .y1(function(d) { return y(d.price); }); var line = d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.price); }); d3.csv("stocks.csv", type, function(error, data) { // Nest data by symbol. var symbols = d3.nest() .key(function(d) { return d.symbol; }) .entries(data); // Compute the maximum price per symbol, needed for the y-domain. symbols.forEach(function(s) { s.maxPrice = d3.max(s.values, function(d) { return d.price; }); }); // Compute the minimum and maximum date across symbols. // We assume values are sorted by date. x.domain([ d3.min(symbols, function(s) { return s.values[0].date; }), d3.max(symbols, function(s) { return s.values[s.values.length - 1].date; }) ]); // Add an SVG element for each symbol, with the desired dimensions and margin. var svg = d3.select("body").selectAll("svg") .data(symbols) .enter().append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // Add the area path elements. Note: the y-domain is set per element. svg.append("path") .attr("class", "area") .attr("d", function(d) { y.domain([0, d.maxPrice]); return area(d.values); }); // Add the line path elements. Note: the y-domain is set per element. svg.append("path") .attr("class", "line") .attr("d", function(d) { y.domain([0, d.maxPrice]); return line(d.values); }); // Add a small label for the symbol name. svg.append("text") .attr("x", width - 6) .attr("y", height - 6) .style("text-anchor", "end") .text(function(d) { return d.key; }); }); function type(d) { d.price = +d.price; d.date = parseDate(d.date); return d; } </script>