Invalid value for<path> attribute in d3.js - d3.js

I am a complete newbie in d3.js and I was working around with some code but it's failing to create the path. Can someone help me to figure out what I am doing wrong?
Link for jsfiddle: http://jsfiddle.net/p8S7p/154/
var data = [
{
data: [
[
1420815600000,
2
],
[
1420826400000,
2
],
[
1420837200000,
2
],
[
1420848000000,
2
],
],
parameter: "t1"
},
{
data: [
[
1420815600000,
2
],
[
1420826400000,
2
],
[
1420837200000,
2
],
[
1420848000000,
2
],
],
parameter: "t2"
}
];
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.linear()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
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[0]); })
.y(function (d) {
return y(d[1]);
});
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 + ")");
var cities = [];
for (var i = 0; i < data.length; i++) {
var t = {};
t["name"] = data[i].parameter;
t["values"] = [];
for (var j = 0; j < data[i].data.length; j++) {
var m = {};
m["date"] = data[i].data[j][0];
m["temperature"] = data[i].data[j][1];
t["values"].push(m);
}
cities.push(t);
}
x.domain(d3.extent(data[0].data, function (d) {
return d[0];
}));
y.domain([
d3.min(cities, function (c) {
return d3.min(c.values, function (v) {
return v.temperature;
});
}),
d3.max(cities, function (c) {
return d3.max(c.values, function (v) {
return v.temperature;
});
})]);
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("Temperature (ºF)");
var city = svg.selectAll(".city")
.data(cities)
.enter().append("g")
.attr("class", "city");
city.append("path")
.attr("class", "line")
.attr("d", function (d) {
return line(d.values);
});
Its meant to be dates on x -axis. How should I parse milliseconds dates to D3 time format?

In your code
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return x(d[0]); }) //this is incorrect why d[0]
.y(function (d) {
return y(d[1]); //this is incorrect why d[1]
});
should have been
var line = d3.svg.line()
.interpolate("basis")
.x(function (d) { return x(d.date); })
.y(function (d) {
return y(d.temperature);
});
Coz that's how you have parsed your data here
var cities = [];
for (var i = 0; i < data.length; i++) {
var t = {};
t["name"] = data[i].parameter;
t["values"] = [];
for (var j = 0; j < data[i].data.length; j++) {
var m = {};
m["date"] = data[i].data[j][0];//storing this in date
m["temperature"] = data[i].data[j][1];//storing it in temperature
t["values"].push(m);
}
cities.push(t);
}
Working code here
Hope this helps!

Related

Cannot read property 'values' of null

I am following this example, but I am using d3 v4. My d.date have no values. Can't figure out why. The csv file has correct time format. Can you help me?
<script type="text/javascript">
var margin = {top: 20, right: 80, bottom: 30, left: 50},
w = 800 - margin.left - margin.right,
h = 600 - margin.top - margin.bottom;
var x = d3.scaleTime()
.domain([new Date("January 1, 2012"), new Date("May 31, 2017")])
.range([0, w]);
var y = d3.scaleLinear()
.range([h, 0]);
var xAxis = d3.axisBottom()
.scale(x)
.tickFormat(d3.timeFormat("%m/%Y"));
var yAxis = d3.axisLeft()
.scale(y)
var parseDate = d3.timeParse("%d%m%Y");
console.log(parseDate);
var color = d3.scaleOrdinal(d3.schemeCategory10);
var line = d3.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.stat); });
var svg = 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 + ")");
svg.append("svg:g")
.attr("class", "x_axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
svg.append("svg:g")
.attr("class", "y_axis")
.call(yAxis)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", "0.71em")
.attr("fill", "#000")
.text("Numbers");
var menu = d3.select("#menu select")
.on("change", change);
d3.csv("Data4.csv", function(csv) {
console.log(csv);
medias = csv
redraw();
});
d3.select(window)
.on("keydown", function() { altKey = d3.event.altKey; })
.on("keyup", function() { altKey = false; });
var altKey;
function change() {
clearTimeout(timeout);
d3.transition()
.duration(altKey ? 7500 : 1500)
.each(redraw);
}
function redraw() {
var nested = d3.nest()
.key(function(d) { return d.indicatorCode;})
.object(medias)
var series = menu.property("value");
var data = nested[series];
console.log(data);
var keyring = d3.keys(data[0]).filter(function(key) {
return (key !== "Sel_name" && key !== "monthCode" && key !== "indicatorCode" && key !== "date");
// console.log(keyring);
});
var transpose = keyring.map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: new Date(parseDate(d.date)), stat: d[name]};
})
};
});
console.log(transpose);
x.domain([
d3.min(transpose, function(c) { return d3.min(c.values, function(d) { return d.date; }); }),
d3.max(transpose, function(c) { return d3.max(c.values, function(d) { return d.date; }); })
]);
y.domain([
d3.min(transpose, function(c) { return d3.min(c.values, function(d) { return d.stat; }); }),
d3.max(transpose, function(c) { return d3.max(c.values, function(d) { return d.stat; }); })
]);
var media = svg.selectAll(".media")
.data(transpose)
.enter().append("g")
.attr("class", "media")
.attr("id", function(d) { return d.name; });
media.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
media.append("text")
.attr("class", "names")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.stat) + ")"; })
.attr("x", 4)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
var mediaUpdate = d3.transition(media);
mediaUpdate.select("path")
.attr("d", function(d) { return line(d.values); });
mediaUpdate.select("text")
.attr("transform", function(d) { return "translate(" + x(d.values[d.values.length - 1].date) + "," + y(d.values[d.values.length - 1].stat) + ")"; });
d3.transition(svg).select("y_axis")
.call(yAxis);
d3.transition(svg).select("x_axis")
.attr("transform", "translate(0," + h + ")")
.call(xAxis);
}
var timeout = setTimeout(function() {
menu.property("value", "NSPM").node().focus();
change();
}, 7000);
function smedia() {
var chkbox = document.getElementById("statmedia");
if (chkbox.checked) {
document.getElementById("media5").style.cssText = "opacity:1;",
document.getElementById("media6").style.cssText = "opacity:1;",
document.getElementById("media7").style.cssText = "opacity:1;",
document.getElementById("media8").style.cssText = "opacity:1;"
} else {
document.getElementById("media5").style.cssText = "",
document.getElementById("media6").style.cssText = "",
document.getElementById("media7").style.cssText = "",
document.getElementById("media8").style.cssText = "";
}};
function nstmedia() {
var chkbox = document.getElementById("nonstmedia")
if (chkbox.checked) {
document.getElementById("media1").style.cssText = "opacity:1;",
document.getElementById("media2").style.cssText = "opacity:1;",
document.getElementById("media3").style.cssText = "opacity:1;",
document.getElementById("media4").style.cssText = "opacity:1;",
document.getElementById("media5").style.cssText = "opacity:1;",
document.getElementById("media6").style.cssText = "opacity:1;",
document.getElementById("media7").style.cssText = "opacity:1;",
document.getElementById("media8").style.cssText = "opacity:1;",
document.getElementById("media9").style.cssText = "opacity:1;"
} else {
document.getElementById("media1").style.cssText = "",
document.getElementById("media2").style.cssText = "",
document.getElementById("media3").style.cssText = "",
document.getElementById("media4").style.cssText = "",
document.getElementById("media5").style.cssText = "",
document.getElementById("media6").style.cssText = "",
document.getElementById("media7").style.cssText = "",
document.getElementById("media8").style.cssText = "",
document.getElementById("media9").style.cssText = "";
}};
</script>
My cvs file looks like following:
Sel_name,indicatorCode,date,monthCode,media1,media2,media3,media4,media5,media6,media7,media8,media9,media10,media11,media12,media13
Num_posts_pmon,NPPM,31/01/2012,m1201,217,146,0,1114,0,0,0,0,0,0,0,0,54
Num_posts_pmon,NPPM,29/02/2012,m1202,159,161,0,1402,0,0,0,0,0,0,0,0,31
Num_posts_pmon,NPPM,31/03/2012,m1203,8,7,0,1212,0,0,0,24,0,0,0,28,17
Num_posts_pmon,NPPM,30/04/2012,m1204,10,14,0,1004,0,0,0,111,0,0,26,28,6
Num_posts_pmon,NPPM,31/05/2012,m1205,15,73,0,1070,0,0,0,76,0,0,127,557,6
Num_posts_pmon,NPPM,30/06/2012,m1206,102,396,0,834,0,0,0,97,0,0,23,893,1
Num_posts_pmon,NPPM,31/07/2012,m1207,148,276,0,993,0,0,0,63,0,0,67,602,0
Num_posts_pmon,NPPM,31/08/2012,m1208,167,189,0,909,34,0,0,54,0,0,31,606,3
Num_posts_pmon,NPPM,30/09/2012,m1209,176,196,0,991,254,0,0,80,0,0,81,608,8
Num_posts_pmon,NPPM,31/10/2012,m1210,121,184,0,1064,190,0,0,41,0,0,93,600,100
Num_posts_pmon,NPPM,30/11/2012,m1211,107,137,0,1301,78,0,0,68,0,0,110,416,116
Num_posts_pmon,NPPM,31/12/2012,m1212,73,108,0,1190,40,0,0,41,0,0,163,306,158
Num_posts_pmon,NPPM,31/01/2013,m1301,98,122,0,1266,121,0,0,53,0,0,137,329,201
Num_posts_pmon,NPPM,28/02/2013,m1302,92,108,0,1248,175,0,0,32,0,0,86,221,205
Num_posts_pmon,NPPM,31/03/2013,m1303,95,101,0,1330,88,0,0,59,0,0,112,160,243
Num_posts_pmon,NPPM,30/04/2013,m1304,122,127,0,1764,280,0,0,61,0,0,151,264,189
Num_posts_pmon,NPPM,31/05/2013,m1305,89,90,0,1645,630,0,785,123,715,0,144,275,203
Num_posts_pmon,NPPM,30/06/2013,m1306,83,103,0,1541,830,0,1105,130,1425,0,99,260,268
Num_posts_pmon,NPPM,31/07/2013,m1307,89,111,0,1468,895,0,1515,133,1443,0,40,145,318
Num_posts_pmon,NPPM,31/08/2013,m1308,82,86,0,1508,1105,0,1720,125,1488,0,65,227,250
Num_posts_pmon,NPPM,30/09/2013,m1309,264,117,0,1690,1900,14,1507,195,2515,0,105,226,251
Your specifier is wrong, you're forgetting the forward slashes.
Since your dates are like this:
31/01/2012
Your specifier should be:
var parseDate = d3.timeParse("%d/%m/%Y");
Besides that, you don't need the new Date in the map function:
var date = "31/01/2012";
var parseDate = d3.timeParse("%d/%m/%Y");
console.log(parseDate(date))
console.log(new Date(parseDate(date)))
<script src="https://d3js.org/d3.v4.min.js"></script>

d3 center tick and x-axis label when single value

I have the following d3 code:
var json = [
{
date: "05/17",
numTags: 23
}
];
d3.select('summary-graph').selectAll('*').remove();
var svg = d3.select("summary-graph"),
margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = svg.attr("width") - margin.left - margin.right,
height = svg.attr("height") - margin.top - margin.bottom;
var parseTime = d3.timeParse("%m/%y");
var svg = d3.select("summary-graph").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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function (d) {
console.log(d);
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function (d) {
return d.date;
}))
.nice();
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function (d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function (d) {
return xScale(d.date);
})
.y(function (d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) { return "blue" })
.attr("cx", function(d, i) { return xScale(d.date) })
.attr("cy", function(d, i) { return yScale(d.numTags) })
.attr("r", function(d, i) { return 10 });
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size","14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
Which produces the following visualization:
I'm trying to figure out how to center the tick mark and show the x-axis label when there is only 1 data point like this. At 2 data points, I don't love how it still sets the tick marks at the extreme ends of the x-axis. For 3 data points and above, it looks nice (thanks to .nice() it seems).
Any help?
Based on Gerado's response, I was able to get close. The last sticking point is that the left side of the X-axis now has the month (March) despite no data for that day.
Fixed:
changed .ticks(json.length) to .ticks(d3.timeMonth.every(1))
Since you are using only a single data point, your date scale has a domain in which the lower and upper values are the same:
[
Mon May 01 2017 00: 00: 00 GMT + 1000,
Mon May 01 2017 00: 00: 00 GMT + 1000
]
For putting that circle in the middle of the x axis you have to set different values for the scale's domain.
There are several ways for doing that. My proposed solution here involves verifying if the domain's values are the same...
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
... and, if they are, changing them. In this case, I'm subtracting one day from the lower limit and adding one day to the upper limit:
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
Check the result:
var json = [{
date: "05/17",
numTags: 23
}];
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 400,
height = 200;
var parseTime = d3.timeParse("%m/%y");
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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {
return d.date;
}))
.nice();
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function(d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) {
return "blue"
})
.attr("cx", function(d, i) {
return xScale(d.date)
})
.attr("cy", function(d, i) {
return yScale(d.numTags)
})
.attr("r", function(d, i) {
return 10
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size", "14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>
EDIT: As you asked in your edit, when you have two data values my solution will create additional ticks on the limits, which is the expected behaviour:
var json = [{
date: "05/17",
numTags: 23
}, {
date: "05/17",
numTags: 17
}];
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 400,
height = 200;
var parseTime = d3.timeParse("%m/%y");
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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {
return d.date;
}))
.nice();
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function(d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) {
return "blue"
})
.attr("cx", function(d, i) {
return xScale(d.date)
})
.attr("cy", function(d, i) {
return yScale(d.numTags)
})
.attr("r", function(d, i) {
return 10
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size", "14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>
There are several ways for removing those ticks. One of them is using tickValues:
.tickValues(data.map(function(d){ return d.date}))
Here is the demo:
var json = [{
date: "05/17",
numTags: 23
}, {
date: "05/17",
numTags: 17
}];
var margin = {
top: 20,
right: 30,
bottom: 30,
left: 40
},
width = 400,
height = 200;
var parseTime = d3.timeParse("%m/%y");
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 + ")");
// Get the data
var data = json;
// format the data
data.forEach(function(d) {
d.date = parseTime(d.date);
d.numTags = +d.numTags;
});
// set the ranges
var xScale = d3.scaleTime()
.range([0, width])
.domain(d3.extent(data, function(d) {
return d.date;
}))
.nice();
if (xScale.domain()[0].getTime() == xScale.domain()[1].getTime()) {
var dateLess = d3.timeDay.offset(xScale.domain()[0], -1);
var dateMore = d3.timeDay.offset(xScale.domain()[0], 1);
xScale.domain([dateLess, dateMore])
}
var yScale = d3.scaleLinear()
.range([height, 0])
.domain([0, d3.max(data, function(d) {
return Math.max(d.numTags);
})])
.nice();
// define the 1st line
var tagLine = d3.line()
.x(function(d) {
return xScale(d.date);
})
.y(function(d) {
return yScale(d.numTags);
});
// Axes
var xAxis = d3.axisBottom()
.scale(xScale)
.ticks(json.length)
.tickSizeOuter(0)
.tickValues(data.map(function(d){ return d.date}))
.tickFormat(d3.timeFormat('%B %Y'));
var yAxis = d3.axisLeft().scale(yScale);
svg.append("path")
.data([data])
.attr("class", "line")
.style("stroke", "blue")
.attr("d", tagLine);
var points = svg.selectAll(".point")
.data(data)
.enter().append("svg:circle")
.attr("stroke", "green")
.attr("fill", function(d, i) {
return "blue"
})
.attr("cx", function(d, i) {
return xScale(d.date)
})
.attr("cy", function(d, i) {
return yScale(d.numTags)
})
.attr("r", function(d, i) {
return 10
});
// Add the X Axis
svg.append("g")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.style("font-size", "14px");;
// Add the Y Axis
svg.append("g")
.call(yAxis);
<script src="https://d3js.org/d3.v4.js"></script>

Trying to transition d3v4 linegraph data from one dataset to a dataset with a different scale

I have a line graph which looks fine. The data set is mostly random data with one big spike. The second dataset is just the log2 of each value. I can transition between the two and it looks great. The y axis is transitioning too. But the scale of the line is not transitioning. Not sure how to get the line to update with the right scale.
$(function() {
var margin = { top: 300, right: 100, bottom: 100, left: 100 },
width = 1400 - margin.right - margin.left,
height = 1080 - margin.top - margin.bottom;
var parseTime = d3.timeParse("%H:%M:%S");
var x = d3.scaleTime().range([0, width]);
var y = d3.scaleLinear().range([height, 0]);
var log2y = d3.scaleLinear().range([height, 0]);
var valueline = d3.line()
.curve(d3.curveMonotoneX)
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.value); });
var log2valueline = d3.line()
.x(function (d) { return x(d.date); })
.y(function (d) { return y(Math.log2(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.select("body").attr("align", "center");
d3.csv("data.csv", function (error, data) {
if (error) {
throw error;
}
var log2data = [];
var log10data = [];
data.forEach(function (d, index) {
d.date = parseTime(d.date);
d.value = +d.value;
log2data[index] = { "date": d.date, "value": Math.log2(+d.value) };
log10data[index] = { "date": d.date, "value": Math.log10(+d.value) };
});
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain([0, d3.max(data, function (d) { return d.value; })]);
log2y.domain([0, d3.max(log2data, function (d) { return d.value; }) ]);
svg.append("path")
.data([data])
.attr("class", "line")
.attr("d", valueline);
svg.append("g")
.attr("class", "xaxis")
.attr("class", "chart")
.attr("transform", "translate(0, " + height + ")")
.call(d3.axisBottom(x).ticks(d3.timeMinute.every(10)));
var yaxis = svg.append("g")
.attr("class", "yaxis")
.attr("class", "chart")
.call(d3.axisLeft(y).ticks(5));
yaxis
.transition().duration(500).delay(2000)
.call(d3.axisLeft(log2y).ticks(4));
svg.selectAll("path")
.data([log2data])
.transition().duration(500).delay(2000)
.attr("d", valueline);
});
});
So here is the chart before the transition:
And here is the chart after the transition:
Adding the update from Harpal, I see this:
It's because the new line is still using the old scale (valueline)
Change this:
svg.selectAll("path")
.data([log2data])
.transition().duration(500).delay(2000)
.attr("d", valueline);
to this:
svg.selectAll("path")
.data([log2data])
.transition().duration(500).delay(2000)
.attr("d", log2valueline);
So the solution, as with so many things, is to go for a walk, get something to eat, and return with a fresh look. I rewrote it, based on what I learned thus far and have a working solution:
$(function () {
var margin = { top: 300, right: 100, bottom: 100, left: 100 },
winwidth = $(window).width(),
winheight = $(window).height(),
width = winwidth - margin.right - margin.left,
height = winheight - margin.top - margin.bottom,
x = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]);
var parseTime = d3.timeParse("%H:%M:%S");
var valueline = d3.line()
.curve(d3.curveMonotoneX)
.x(function (d) { return x(d.date); })
.y(function (d) { return y(d.value); });
var svg = d3.select('body').append('svg')
.attr("width", winwidth)
.attr("height", winheight)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var path = svg.append("path");
var xaxis = svg.append("g")
.attr("class", "xaxis")
.attr("class", "chart")
.attr("transform", "translate(0, " + height + ")");
var yaxis = svg.append("g")
.attr("class", "yaxis")
.attr("class", "chart");
function step1(sourcedata) {
var data = sourcedata.data;
var y = d3.scaleLinear().range([height, 0]);
y.domain([0, d3.max(data, function (d) { return Math.log2(d.value); })]);
valueline = d3.line()
.curve(d3.curveMonotoneX)
.x(function (d) { return x(d.date); })
.y(function (d) { return y(Math.log2(d.value)); });
path
.data([data])
.transition()
.attr("class", "line")
.attr("d", valueline);
yaxis
.transition()
.call(d3.axisLeft(y).ticks(4));
}
d3.select("body").attr("align", "center");
d3.csv("data.csv", function (error, data) {
if (error) {
throw error;
}
data.forEach(function (d) {
d.date = parseTime(d.date);
d.value = +d.value;
});
x.domain(d3.extent(data, function (d) { return d.date; }));
y.domain([0, d3.max(data, function (d) { return d.value; })]);
path
.data([data])
.attr("class", "line")
.attr("d", valueline);
xaxis
.attr("transform", "translate(0, " + height + ")")
.call(d3.axisBottom(x).ticks(d3.timeMinute.every(10)));
yaxis.call(d3.axisLeft(y).ticks(5));
$("#rescale").click(data, step1);
});
});
And the graph works as follows:

2 completely different d3 charts on same page

I'm trying to get 2 completely different d3 charts (2 line charts but totally different data - one with several lines and negative data, other with one line positive data) on the same page.
Right now, I only get the first one to be generated and shown correctly on the HTML page, the second chart doesn't show at all (not even svg container is generated).
Here is my code:
(function() {
// Get the data
d3.json("../assets/js/json/temperature.json", function(data) {
// Set the dimensions of the canvas / graph
var margin = {top: 30, right: 20, bottom: 30, left: 25},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
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(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
// Define the line
var valueline = d3.svg.line()
.x(function(d) { return x(d.temps); })
.y(function(d) { return y(d.temperature); });
// prepare data
data.forEach(function(d) {
d.temps = parseDate(d.temps);
d.temperature = +d.temperature;
});
// Adds the svg canvas
var svg = d3.select("#graphTemp")
.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 + ")");
// Scale the range of the data on domain
x.domain(d3.extent(data, function(d) { return d.temps; }));
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 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)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Temperatures");
});
})();
(function(){
// loads the data and loads it into chart - main function
d3.json("../assets/js/json/maitrise.json", function(data) {
var m = {top: 20, right: 5, bottom: 30, left: 40},
w = 70 - m.left - m.right,
h = 30 - m.top - m.bottom;
var x = d3.scale.linear().domain([0, data.length]).range([0 + m.left, w - m.right]);
var y = d3.scale.linear()
.rangeRound([h, 0]);
var line = d3.svg.line()
.interpolate("cardinal")
.x(function(d,i) { return x(i); })
.y(function (d) { return y(d.value); });
var color = d3.scale.ordinal()
.range(["#28c6af","#ffd837","#e6443c","#9c8305","#d3c47c"]);
var svg2 = d3.select("#maitrisee").append("svg")
.attr("width", w + m.left + m.right)
.attr("height", h + m.top + m.bottom)
.append("g")
.attr("transform", "translate(" + m.left + "," + m.top + ")");
// prep axis variables
var xAxis2 = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis2 = d3.svg.axis()
.scale(y)
.orient("left");
//console.log("Inital Data", data);
var labelVar = 'id'; //A
var varNames = d3.keys(data[0])
.filter(function (key) { return key !== labelVar;}); //B
color.domain(varNames); //C
var seriesData = varNames.map(function (name) { //D
return {
name: name,
values: data.map(function (d) {
return {name: name, label: d[labelVar], value: +d[name]};
})
};
});
console.log("seriesData", seriesData);
y.domain([
d3.min(seriesData, function (c) {
return d3.min(c.values, function (d) { return d.value; });
}),
d3.max(seriesData, function (c) {
return d3.max(c.values, function (d) { return d.value; });
})
]);
var series = svg2.selectAll(".series")
.data(seriesData)
.enter().append("g")
.attr("class", function (d) { return d.name; });
series.append("path")
.attr("class", "line")
.attr("d", function (d) { return line(d.values); })
.style("stroke", function (d) { return color(d.name); })
.style("stroke-width", "2px")
.style("fill", "none");
});
})();
OK, I found where the error was coming from. There was a piece of javascript in the middle of the HTML page that stopped d3 to generate the second graph further down in the page.
Thanks for all the help!

d3js - TypeError: string is undefined

I don't understand this error:
TypeError: string is undefined
function d3_time_parse(date, template, string, j) {
var c, p, i = 0, n = template.length, m = string.length;
...
Here my code:
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y%m%d").parse;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var color = d3.scale.category10();
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.index); });
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("data.csv", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "date"; }));
data.forEach(function(d) {
d.date = parseDate(d.date);
});
var indexes = color.domain().map(function(name) {
return {
name: name,
values: data.map(function(d) {
return {date: d.date, index: +d[name]};
})
};
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([
d3.min(indexes, function(c) { return d3.min(c.values, function(v) { return v.index; }); }),
d3.max(indexes, function(c) { return d3.max(c.values, function(v) { return v.index; }); })
]);
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("Variation (%)");
var index = svg.selectAll(".index")
.data(indexes)
.enter().append("g")
.attr("class", "index");
index.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.name); });
index.append("text")
.datum(function(d) { return {name: d.name, value: d.values[d.values.length - 1]}; })
.attr("transform", function(d) { return "translate(" + x(d.value.date) + "," + y(d.value.index) + ")"; })
.attr("x", 3)
.attr("dy", ".35em")
.text(function(d) { return d.name; });
});
and my csv file look like this:
Date,DAX,CAC40,FTSE,NASDAQ,Other
20060407,-0.000712859,-0.009013212,0.010819606,0.009846526,0.003082604
20060413,-0.007765968,-0.024263398,0.011238971,0.004128621,0.005952774
20060421,0.02261859,0.00330204,0.028734861,0.001688981,0.003459211
20060428,0.007170521,-0.007531405,0.010534438,-0.002416181,0.004012361
...
Could someone please help me?
thx
skeut
Date,DAX,CAC40,FTSE,NASDAQ,Other
JavaScript variable names are case sensitive, so when parsing CSV file with headers as above you need to refer to fields with:
d.Date // note the uppercase D
d.DAX // note all uppercase
Here's an example from d3 wiki https://github.com/mbostock/d3/wiki/CSV#wiki-parse
Year,Make,Model,Length
1997,Ford,E350,2.34
2000,Mercury,Cougar,2.38
When parsed with d3's CSV parser, the resulting data will be represented by the following array:
[
{"Year": "1997", "Make": "Ford", "Model": "E350", "Length": "2.34"},
{"Year": "2000", "Make": "Mercury", "Model": "Cougar", "Length": "2.38"}
]
Note the uppercase object keys. To access the year of the first entry, a "Year" with an uppercase Y in data[0].Year would be necessary.
Thus in your forEach function you'll need:
data.forEach(function (d) {
d.Date = parseDate(d.Date);
});
... and later on:
return {date: d.Date, index: +d[name]};

Resources