I'm new to D3 charts and I'm getting an error saying 'Error: Problem Parsing' when trying to run my code. The code and error can be seen below. I have no idea what the problem is except it has something to do with parsing the 'd.value'. Both X and Y axis show up as well as the X axis dates. But there are no lines. The value coming in is already a number, but I've tried to use parseFloat, parseInt, and parseDouble to make it work. I'm out of ideas.
Error: Problem parsing d="M0,NaNL0.47187163062091714,NaNL0.9437432612418343,NaNL1.4156148918627514,NaNL1.8874865224836685,NaNL2.3593581531045857,NaNL2.8312297837255027, etc. etc.
function drawLineChart(element, chartData){
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 380 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
var parseDateD3 = d3.time.format("%d-%m-%y").parse;
var defaultMax = 50;
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.ticks(6)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.ticks(6)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
var svg = d3.selectAll(element).append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.style("margin", "auto")
.style("background-color", "white")
.style("border", "2px solid white")
.style("border-radius", "25px")
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//d3.tsv("/resources/sampledata/data.tsv", function(error, data) {
chartData.forEach(function(d) {
var day = JSON.stringify(d.day.date);
var month = JSON.stringify(d.day.month);
var year = JSON.stringify(d.day.year);
if(day < 10) day = "0" + day;
if(month < 10) month = "0" + month;
year = year.substring(1, year.length);
d.date = parseDateD3(day + "-" + month + "-" + year);
var NUMBER = parseInt(d.value);
d.number = +NUMBER;
});
x.domain(d3.extent(chartData, function(d,i) { return d.date; }));
y.domain(d3.extent(chartData, function(d) { return d.number; }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("path")
.datum(chartData)
.attr("class", "line")
.attr("d", line);
svg.append("rect")
.attr("class", "goal")
.style("opacity", 0.2)
.attr("width", width)
.attr("height", height - defaultMax)
.attr("transform", "translate(0," + defaultMax + ")");
}
In the definition of your line, you should have
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.number); });
instead of
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.close); });
The code was referencing .close and you're setting and using .number elsewhere.
Related
Why is the y-axis is not aligned with the graph. Graph response height exceeds y-axis data.
Expected output should not have graph height overflow from plot area/exceed y axis height.
Here is my javascript:
function getD3Chart(chartData){
var formattime = d3.time.format("%a-%d");
var widther = window.outerWidth - 35;
if(widther > 750){
widther = 430;
}
var margin = {top: 20, right: 20, bottom: 30, left: 30},
width = widther - margin.left - margin.right,
height = 235 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%Y:%H").parse,
bisectDate = d3.bisector(function(d) { return d.date; }).left,
formatValue = d3.format(",.3f"), // its use for after decimal we can show number of fractional digit
formatCurrency = function(d) { return 1000*formatValue(d)+"ms, "; };
var x = d3.time.scale()
.range([0, width]);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.innerTickSize(0)
.outerTickSize(0)
.tickPadding(10)
.tickFormat(formattime)
.ticks(7);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.innerTickSize(0)
.outerTickSize(0);
var area = d3.svg.area()
.x(function(d) { return x(d.date); })
.y0(height)
.y1(function(d) { return y(d.avgResponse); });
var line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.avgResponse); });
var svg = d3.select("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 data = chartData.map(function(d) {
return{
date : parseDate(d.date),
avgResponse : d.avgResponse
};
});
data.sort(function(a, b) {
return a.date - b.date;
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.avgResponse; })]);
svg.append("path")
.data([data])
.attr("class", "area")
.attr("d", area);
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.style("position", "absolute")
.style("font-weight", "bold")
.text("Avg ResponseTime in ms");
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.style("position", "absolute")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.style("position", "absolute")
.call(yAxis);
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
var focus = svg.append("g")
.attr("class", "focus")
.style("display", "none");
focus.append("circle")
.attr("r", 6.5);
focus.append("text")
.attr("x", 9)
.attr("dy", ".35em");
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.attr("background-color", "#EDE3D1")
.attr('opacity', 0)
.on("mouseover", function() { focus.style("display", null); })
.on("mouseout", function() { focus.style("display", "none"); })
.on("mousemove", mousemove);
function mousemove() {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var x0 = x.invert(d3.mouse(this)[0]),
i = bisectDate(data, x0, 1),
d0 = data[i - 1],
d1 = data[i],
d = x0 - d0.date > d1.date - x0 ? d1 : d0;
var hour = d.date.getHours();
hour = (hour < 10)? "0"+hour : hour;
focus.attr("transform", "translate(" + x(d.date) + "," + y(d.avgResponse) + ")");
focus.select("text").text(formatCurrency(d.avgResponse) +" "+months[d.date.getMonth()]+" "+ d.date.getDate()+"th " +hour+":00h");
focus.select("text").attr("class", "graphDataClass");
if(d3.mouse(this)[0] > 260) {
focus.select("text").attr("x", -120);
}else{
focus.select("text").attr("x", 9);
}
}
}
I've been fiddling with this for a few days now and I either get the error in the title, or I get "key.call is not a function", and I don't know why... basically the point of the script is to load different csv files based on the selection made in the dropdown. Without all the dropdown stuff, the script works fine, but once I introduce the dropdown script it starts bugging out and I can't figure out why. Below is the script, and I'll attach a sample of the kind of csv I'm working with if that helps at all.
Thanks a ton in advance!
CSV example: https://www.dropbox.com/s/24zopp43r3y1ft6/PCC-edit.csv?dl=0 (QC = QuantityCharged in this example)
<svg class="chart"></svg>
<select onchange="loadData()" id="metric">
<option>A-codes</option>
<option>Anesthesia</option>
<option>C-codes</option>
<option>Clinical Components (NRV)</option>
<option>E-Codes</option>
<option>Emerging Technology</option>
<option>Evaluation & Management</option>
<option>G-codes</option>
<option>J-codes</option>
<option>L-codes</option>
<option>Medicine</option>
<option>Pathology & Laboratory</option>
<option>P-codes</option>
<option>Q-codes</option>
<option>Radiology</option>
<option>Surgery</option>
<option>V-codes</option>
</select>
<script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
<script>
var svg = d3.select("svg"),
margin = {top:10, right: 720, bottom: 5, left: 720},
width = +svg.attr("width") + margin.left + margin.right,
height = +svg.attr("height") + margin.top + margin.bottom;
var g = svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var x = d3.scale.linear()
.range([3, width]);
var y = d3.scale.ordinal()
.range([height, 1]);
var chart = d3.select(".chart")
.attr("width", width);
var parseRow = function(row) {
return {
subcategory: row.Subcategory,
quantityCharged: parseFloat(row.QuantityCharged)
}
};
//d3
var loadData = function(data) {
var metric = document.getElementById('metric').selectedOptions[0].text;
var dataFile = 'data/' + metric + '.csv'
d3.csv(dataFile, parseRow, function(error, data) {
x.domain([1, d3.max(data, function(d) { return d.QuantityCharged; })]);
y.domain([1, d3.max(data, function(d) { return d.Charge; })])
});
chart.attr("height", height);
var bar = chart.selectAll("g")
.data("width", data)
.enter().append("g")
.attr("transform", function(d, i) { return "translate(0," + i * height + ")"; });
bar.append("rect")
.attr("width", function(d) { return x(d.QuantityCharged); })
.attr("height", height - 1);
bar.append("text")
.attr("x", function(d) { return x(d.QuantityCharged) + 10; })
.attr("y", height / 2)
.attr("dy", ".35em")
.text(function(d) { return d.QuantityCharged + " -- " + d.Charge; });
var xAxis = d3.svg.axis()
.scale(x)
.ticks(20)
.orient("top")
var yAxis = d3.svg.axis()
.scale(y)
.ticks(24)
.orient("left");
var line = d3.svg.line()
.x(function(d) { return x(d.QuantityCharged); })
.y(function(d) { return y(d.QuantityCharged); });
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
svg.append("path")
.attr("class", "line")
.attr("data", line);
function type(d) {
d.QuantityCharged = +d.QuantityCharged; // coerce to number
d.Subcategory = d.Subcategory;
return d;
}};
function Subcategory(csv) {
d3.text(dataFile, parseRow, function(text) {
var Subcategory = d3.csv.parseRows(text),
Charge = d3.csv.parseRows(text);
})}
loadData();
</script>
I'm learning d3js using various examples found online.
I've been trying to plot a chart with dual Y axis and an X-axis. The Y axis on the left side would plot a bar chart against the X-axis and the Y-axis on the right side would plot a line chart against X-axis. The Bar graph plots as exactly as required but the line graph does not. The X-axis is date (2015-10-15 04:10). Following this example.
The code I wrote
var margin = {top: 50, right: 50, bottom: 100, left: 50},
width = 900 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%m/%d/%Y %H:%M:%S").parse;
var x = d3.scale.ordinal().rangeRoundBands([0, width], .05);
var yTxnVol = d3.scale.linear().range([height, 0]);
var yResTime = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
var yAxis = d3.svg.axis()
.scale(yTxnVol)
.orient("left")
var yAxis2 = d3.svg.axis()
.scale(yResTime)
.orient("right")
.ticks(10);
var svg = d3.selectAll("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("../res/data.csv", function(error, data) {
data.forEach(function(d) {
d.AVRG_RESP_TIME = +d.AVRG_RESP_TIME;
d.TXN_VOL = +d.TXN_VOL;
});
x.domain(data.map(function(d) { return d.TYM; }));
yTxnVol.domain([0, d3.max(data, function(d) { return d.TXN_VOL+50; })]);
yResTime.domain([0, d3.max(data, function(d) { return d.AVRG_RESP_TIME+50; })]);
var minDate = d3.min(data, function(d){return d.TYM});
var maxDate = d3.max(data, function(d){ return d.TYM});
var xScale = d3.time.scale().range([0,width]);//.domain([minDate, maxDate]);
xScale.domain(d3.extent(data, function(d) { return new Date(d.TYM); }));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)" );
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
svg.append("g")
.attr("class","y axis")
.attr("transform","translate("+width+ ", 0)")
.call(yAxis2)
svg.selectAll("bar")
.data(data)
.enter().append("rect")
.attr("class", "yhover")
.attr("x", function(d) { return x(d.TYM); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return yTxnVol(d.TXN_VOL); })
.attr("height", function(d) { return height - yTxnVol(d.TXN_VOL); })
var line = d3.svg.line()
.x(function(d) { return xScale(new Date(d.TYM));})
.y(function(d) { return d.AVRG_RESP_TIME; });
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
The Output Trying to make this to a meaningful line graph. Got NaN error while formatting the dates.
Could someone help me to make this a proper line graph ?
The csv data sample
TYM, AVRG_RESP_TIME, TXN_VOL
2015-10-15 04:00:00, 12, 170
2015-10-15 04:10:00, 18, 220
2015-10-15 04:20:00, 28, 251
2015-10-15 05:00:00, 19, 100
First, fix your csv file. It is improperly formatted and should not have spaces after the comma.
Second, You are trying to mix an ordinal scale and a time scale for you xAxis. This isn't going to work. For your use case, just stick with time.
Here's a reworking of your code with explanatory comments:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3#3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
</head>
<body>
<script>
var margin = {
top: 50,
right: 50,
bottom: 100,
left: 50
},
width = 900 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate = d3.time.format("%Y-%m-%d %H:%M:%S").parse;
// x scale should be time and only time
var x = d3.time.scale().range([0, width]);
var yTxnVol = d3.scale.linear().range([height, 0]);
var yResTime = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
var yAxis = d3.svg.axis()
.scale(yTxnVol)
.orient("left")
var yAxis2 = d3.svg.axis()
.scale(yResTime)
.orient("right")
.ticks(10);
var svg = d3.selectAll("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) {
var data = [{"TYM":"2015-10-15 04:00:00","AVRG_RESP_TIME":"12","TXN_VOL":"170"},{"TYM":"2015-10-15 04:10:00","AVRG_RESP_TIME":"18","TXN_VOL":"220"},{"TYM":"2015-10-15 04:20:00","AVRG_RESP_TIME":"28","TXN_VOL":"251"},{"TYM":"2015-10-15 05:00:00","AVRG_RESP_TIME":"19","TXN_VOL":"100"}];
// just make TYM a date and keep it as a date
data.forEach(function(d) {
d.TYM = parseDate(d.TYM);
d.AVRG_RESP_TIME = +d.AVRG_RESP_TIME;
d.TXN_VOL = +d.TXN_VOL;
});
// get our min and max date in milliseconds
// set a padding around our domain of 15%
var minDate = d3.min(data, function(d){
return d.TYM;
}).getTime();
var maxDate = d3.max(data, function(d){
return d.TYM;
}).getTime();
var padDate = (maxDate - minDate) * .15;
x.domain([new Date(minDate - padDate), new Date(maxDate + padDate)]);
yTxnVol.domain([0, d3.max(data, function(d) {
return d.TXN_VOL + 50;
})]);
yResTime.domain([0, d3.max(data, function(d) {
return d.AVRG_RESP_TIME + 50;
})]);
// set an intelligent bar width
var barWidth = (width / x.ticks().length) - 20;
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.style("text-anchor", "end")
.attr("dx", "-.8em")
.attr("dy", "-.55em")
.attr("transform", "rotate(-90)");
svg.append("g")
.attr("class", "y axis")
.call(yAxis)
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + width + ", 0)")
.call(yAxis2)
svg.selectAll("bar")
.data(data)
.enter().append("rect")
.attr("class", "yhover")
.attr("x", function(d) {
// center bar on time
return x(d.TYM) - (barWidth / 2);
})
.attr("width", barWidth)
.attr("y", function(d) {
return yTxnVol(d.TXN_VOL);
})
.attr("height", function(d) {
return height - yTxnVol(d.TXN_VOL);
})
.style("fill","orange");
var line = d3.svg.line()
.x(function(d) {
return x(d.TYM);
})
.y(function(d) {
return d.AVRG_RESP_TIME;
});
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line)
.style("fill","none")
.style("stroke","steelblue")
.style("stoke-width","3px");
// });
</script>
</body>
</html>
The issue with the line graph filling with black was due to improper css. The new css property.
.line {
fill: none;
stroke: darkgreen;
stroke-width: 2.5px;
}
For the dates I formatted it to (%Y-%m-%d %H:%M) format and it worked.
I have a linear y scale with a time series x scale. I want to put an overlay that follows the x/y value (similar to http://bl.ocks.org/mbostock/3902569).
The issue is that I'm not able to transform to the proper x scale value; for example when I mouseover my chart it outputs (this data is correct):
{ y: 0.05, x: "2015-07-26 15:08:47" }
{ y: 0.05, x: "2015-07-26 15:08:47" }
{ y: 0.05, x: "2015-07-26 15:08:47" }
Now I want to use this data to draw a point at that location; the issue is that I cannot replicate the above bl.locks.org example, and the transform isn't able to use the x position as a date; so how can I transform that x date to the point on the chart?
My mousemove is below:
var x = d3.time.scale()
.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 varea = d3.svg.area()
.defined(function(d) { return d.y != null; })
.x(function(d) { return x(parseDate(d.x)); })
.y0(height)
.y1(function(d) { return y(d.y); });
var svg = d3.select(".swatch").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 + ")");
x.domain(d3.extent(data, function(d) { return parseDate(d.x); }));
y.domain([0, d3.max(data, function(d) {
if (d.y >= 1) {
return d.y
}
return 1;
})]);
svg.append("path")
.attr("class", "area")
.attr("d", varea(data));
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var focus = svg.append("g")
.attr("class", "focus")
.attr("display", "none");
focus.append("circle")
.attr("r", 4.5);
focus.append("text")
.attr("x", 9)
.attr("dy", ".35em");
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height)
.on("mouseover", function() {
focus.style("display", null);
})
.on("mouseout", function() {
focus.style("display", "none");
})
.on("mousemove", function() {
var x0 = x.invert(d3.mouse(this)[0]);
var bisect = d3.bisector(function(d) { return parseDate(d.x); }).right;
var item = data[bisect(data, x0)];
focus.attr("transform", "translate(" + x(parseDate(item.x)) + "," + y(item.y) + ")");
focus.select("text").text(item.y);
console.log(x(parseDate(item.x)));
console.log(y(item.y));
});
This code produces errors like the following in the console:
Unexpected value translate(NaN,120) parsing transform attribute.
So, the question is how do I convert the date to a proper coordinate?
Alright, so there were a couple of problems with my code.
I wasn't parsing the x value as a date; so I started parsing it with parseDate (see sample code) and then passed it to the x scale; this allowed me to get proper location on the chart.
The second issue was that display wasn't be set properly (setting it to null in Firefox wasn't allowing it to appear). So I changed that to display: inline; and it started showing up on the chart.
Iam new to D3.i just want to draw a line chart.For that i just put the static values ,its working fine,But when i fetch data from server db graph is not getting properly.Problem iam getting is x and y axis with values are getting.But not getting the line graph.here is the code
// Line chart creation....................................................
var deviceTime = 0;
var margin = { top: 20, right: 80, bottom: 30, left: 50 };
var da = '<%=#display.to_json(:only => [:DeviceTime, :Speed])%>'
var margin = { top: 20, right: 80, bottom: 30, left: 50 };
var dataset=JSON.parse(da.replace(/"/g,'"'));
//test code TODO :need to move somewhere else
var data = [];
for (var vAlue in dataset[0]) {
var tempData = d3.values(dataset[0][vAlue]);
data.push(tempData[1]);
}
// test end
var yExtents = d3.extent(d3.merge(dataset), function (d) { return d.Speed; });
var xExtents = d3.extent(d3.merge(dataset), function (d) { return d.DeviceTime; });
//alert("xevents[0]-------"+xExtents[0] "xevents[1]-------"+xExtents[1]);
var w = 900;
var h = 400;
var padding = 30;
deviceTime = xExtents[1];
//Create scale functions
var xScale = d3.scale.linear()
.domain([xExtents[0], xExtents[1]])
.range([padding, w - padding * 2]);
var yScale = d3.scale.linear()
.domain([0, yExtents[1]])
//.domain([0, 160])
.range([h - padding, padding]);
//Define X axis
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom")
.ticks(10);
//Define Y axis
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(10);
///////////////// need to remove
var line = d3.svg.line()
.x(function (d, i) { return xScale(i); })
.y(function (d, i) { return yScale(d); });
//Create SVG element
var svg = d3.select("#bar-demo")
.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 + ")");
//Create X axis
var hh = svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - padding) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + padding + ",0)")
.call(yAxis);
var path = svg.append("g")
//.attr("clip-path", "url(#clip)")
.append("path")
.data([data])
.attr("class", "line")
.attr("transform", "translate(" + 102 + ",0)")
.attr("d", line);
svg.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 0-margin.left+10)
.attr("x",0-h/2)
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Speed km/h");
svg.append("text")
.attr("y", h)
.attr("x", h)
.attr("dy", "1em")
.style("text-anchor", "middle")
.text("Time Stamp");