I have data with a constant value across multiple dates.
[{"date":"13-Sep-15","data0":2464},{"date":"12-Sep-15","data0":2464},
{"date":"11-Sep-15","data0":2464},{"date":"10-Sep-15","data0":2464},
{"date":"9-Sep-15","data0":2464},{"date":"8-Sep-15","data0":2464},
{"date":"7-Sep-15","data0":2464}]
What are the settings of d3.axis() to get a graph like this?
This needs to work from 1->n y values.
.domain doesn't like an extent of [2464, 2464] no matter the value of .ticks.
Ok I am assuming, want to have distinct y ticks depending on the values in the data.
I am doing some thing like this to get the unique ticks needed in the y axis:
var yData = [];
data.forEach(function (d) {
d.date = parseDate(d.date);
d.close = +d.data0;
yData.push(+d.data0)
});
yData = d3.set(yData).values();//get a set of values for y axis.
Full code here:
// Set the dimensions of the canvas / graph
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the line
var valueline = d3.svg.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.close);
});
// 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 + ")");
data = [{
"date": "13-Sep-15",
"data0": 2464
}, {
"date": "12-Sep-15",
"data0": 2464
}, {
"date": "11-Sep-15",
"data0": 2464
}, {
"date": "10-Sep-15",
"data0": 2464
}, {
"date": "9-Sep-15",
"data0": 2464
}, {
"date": "8-Sep-15",
"data0": 2464
}, {
"date": "7-Sep-15",
"data0": 2464
}];
var yData = [];
data.forEach(function (d) {
d.date = parseDate(d.date);
d.close = +d.data0;
yData.push(+d.data0)
});
yData = d3.set(yData).values()
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").tickValues(yData);
// Scale the range of the data
x.domain(d3.extent(data, function (d) {
return d.date;
}));
y.domain([0, d3.max(data, function (d) {
return d.close;
})]);
// 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);
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Hope this helps!
Figured it out. Here is the graph with the line centered on single y.
// Set the dimensions of the canvas / graph
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
// Set the ranges
var x = d3.time.scale().range([0, width]);
var y = d3.scale.linear().range([height, 0]);
// Define the line
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close) / 2;
});
// 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 + ")");
data = [{
"date": "13-Sep-15",
"data0": 2464
}, {
"date": "12-Sep-15",
"data0": 2464
}, {
"date": "11-Sep-15",
"data0": 2464
}, {
"date": "10-Sep-15",
"data0": 2464
}, {
"date": "9-Sep-15",
"data0": 2464
}, {
"date": "8-Sep-15",
"data0": 2464
}, {
"date": "7-Sep-15",
"data0": 2464
}];
var yData = [];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.data0;
yData.push(+d.data0)
});
yData = d3.set(yData).values()
// Define the axes
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").tickValues(yData);
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain(d3.extent(data, function(d) {
return d.close;
}));
// 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);
d3.select('.y .tick').attr("transform", "translate(0," + height / 2 + ")");
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
Changes:
Translated the y tick down by height / 2:
d3.select('.y .tick').attr("transform", "translate(0," + height / 2 + ")");
Changed y extent:
y.domain(d3.extent(data, function (d) {
return d.close;
}));
Halved the y of the line:
var valueline = d3.svg.line()
.x(function (d) {
return x(d.date);
})
.y(function (d) {
return y(d.close) / 2;
});
Related
I am trying to get responsive d3js charts. I have set the width and height as 100% for the chart have a resize function which should reduce the size . In what I have done so far it just manages to reduce the labels on the x-axis but the line chart remains of the same size.Is the way I am trying to make the responsive the correct way or is their a better way with which any d3js chart(bar/pie/line) could be made responsive.
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = parseInt(d3.select("#chart").style("width")) - margin.left - margin.right,
height = parseInt(d3.select("#chart").style("height")) - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5).tickFormat(function (d) {
return d.replace('SEASONAL_', '');
});;
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function (d) {
return x(d.name);
})
.y(function (d) {
return y(d.count);
});
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 all = [{
"name": "Seasonal Pop",
"code": "SEASONAL_POP",
"children": [{
"name": "SEASONAL_LYQ1",
"code": "SEASONAL_LYQ1",
"count": 1200
}, {
"name": "SEASONAL_LYQ2",
"code": "SEASONAL_LYQ2",
"count": 2000
}, {
"name": "SEASONAL_LYQ3",
"code": "SEASONAL_LYQ3",
"count": 1060
}, {
"name": "SEASONAL_LYQ4",
"code": "SEASONAL_LYQ4",
"count": 2300
}, {
"name": "SEASONAL_CYQ1",
"code": "SEASONAL_CYQ1",
"count": 1300
}, {
"name": "SEASONAL_CYQ2",
"code": "SEASONAL_CYQ2",
"count": 3400
}, {
"name": "SEASONAL_CYQ3",
"code": "SEASONAL_CYQ3",
"count": 4500
}, {
"name": "SEASONAL_CYQ4",
"code": "SEASONAL_CYQ4",
"count": 5500
}]
}];
var data = all[0].children;
data.forEach(function (d) {
// d.name = +d.date ;
d.count = +d.count;
});
// Scale the range of the data
x.domain(data.map(function (d) {
return d.name;
}));
y.domain([0, d3.max(data, function (d) {
return d.count;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
// Define responsive behavior
function resize() {
var width = parseInt(d3.select("#chart").style("width")) - margin.left - margin.right,
height = parseInt(d3.select("#chart").style("height")) - margin.top - margin.bottom;
// Update the range of the scale with new width/height
x.range([0, width]);
y.range([height, 0]);
// Update the axis and text with the new scale
svg.select('.x.axis')
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.select('.y.axis')
.call(yAxis);
// Force D3 to recalculate and update the line
svg.selectAll('.line')
.attr("d", function(d) { return line(d.count); });
// Update the tick marks
xAxis.ticks(Math.max(width/75, 2));
yAxis.ticks(Math.max(height/50, 2));
};
// Call the resize function whenever a resize event occurs
d3.select(window).on('resize', resize);
// Call the resize function
resize();
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
#chart {
width: 100%;
height: 100%;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body><svg id="chart"></svg></body>
Well your code kinda works. Save that you're dealing with two SVGs. The on the page with id="chart" and this one thats appended.
var svg = d3.select("body")
.append("svg")
But its not really a D3 issue its more to do with responsive SVGs. Responsive charts have problems scaling. The X & Y axis can become misrepresented.
One approach is to scale the entire Chart/SVG. Forget about listening to window resize events. Just set a viewBox property on your main svg. And set a static width hight thats too the correct ratio of your chat.
var svg = d3.select("#chart")
.attr("viewBox", "0 0 " + viewWidth + " " + viewHeight)
example
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var width = 500 - margin.left - margin.right,
height = 240 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var y = d3.scale.linear().range([height, 0]);
var xAxis = d3.svg.axis().scale(x)
.orient("bottom").ticks(5).tickFormat(function (d) {
return d.replace('SEASONAL_', '');
});;
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function (d) {
return x(d.name);
})
.y(function (d) {
return y(d.count);
});
var viewWidth = width - margin.left - margin.right;
var viewHeight = height + margin.top + margin.bottom;
var svg = d3.select("#chart")
.attr("viewBox", "0 0 " + viewWidth + " " + viewHeight)
// Get the data
var all = [{
"name": "Seasonal Pop",
"code": "SEASONAL_POP",
"children": [{
"name": "SEASONAL_LYQ1",
"code": "SEASONAL_LYQ1",
"count": 1200
}, {
"name": "SEASONAL_LYQ2",
"code": "SEASONAL_LYQ2",
"count": 2000
}, {
"name": "SEASONAL_LYQ3",
"code": "SEASONAL_LYQ3",
"count": 1060
}, {
"name": "SEASONAL_LYQ4",
"code": "SEASONAL_LYQ4",
"count": 2300
}, {
"name": "SEASONAL_CYQ1",
"code": "SEASONAL_CYQ1",
"count": 1300
}, {
"name": "SEASONAL_CYQ2",
"code": "SEASONAL_CYQ2",
"count": 3400
}, {
"name": "SEASONAL_CYQ3",
"code": "SEASONAL_CYQ3",
"count": 4500
}, {
"name": "SEASONAL_CYQ4",
"code": "SEASONAL_CYQ4",
"count": 5500
}]
}];
var data = all[0].children;
data.forEach(function (d) {
// d.name = +d.date ;
d.count = +d.count;
});
// Scale the range of the data
x.domain(data.map(function (d) {
return d.name;
}));
y.domain([0, d3.max(data, function (d) {
return d.count;
})]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path, .axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
#chart {
width: 100%;
height: 100%;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body><svg id="chart"></svg></body>
I am kind a new to d3.js and want to draw a horizontal grid line based on y coordinate value fiddle , i've tried with if condition at y1 and y2 locations but the lines are overlapping at the top of graph.
Any help is much appreciated.
Your if statement makes little sense to me:
if (y(d) === thresholdValues.minValue) {
return y(d);
}
This means that only when the value in the screen is exactly thresholdValues.minValue (which is 40 in your code) the line will be painted.
Solution: drop the if statement. Actually, I kept the if just to avoid the first gridline, over the x axis:
if (d != 0) {
return y(d);
}
Here is your code with that change:
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var thresholdValues = {
minValue: 40,
maxValue: 85
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
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").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
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 = [{
date: "1-May-12",
close: "58.13"
}, {
date: "30-Apr-12",
close: "53.98"
}, {
date: "27-Apr-12",
close: "67.00"
}, {
date: "26-Apr-12",
close: "89.70"
}, {
date: "25-Apr-12",
close: "99.00"
}];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, 100]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
svg.selectAll("line.horizontalGrid").data(y.ticks(4)).enter()
.append("line")
.attr({
"class": "horizontalGrid",
"x1": margin.right,
"x2": width - margin.right,
"y1": function(d) {
if (d != 0) {
return y(d);
}
},
"y2": function(d) {
if (d != 0) {
return y(d);
}
},
"fill": "none",
"shape-rendering": "crispEdges",
"stroke": "grey",
"stroke-width": "2px",
"opacity": 0.4,
"stroke-dasharray": 8
});
body {
font: 12px Arial;
}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
EDIT: If you want to draw only two lines, at the thresholds, you have to pass their values to data, not the scale ticks:
.data(Object.values(thresholdValues))
Here is the demo:
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
};
var thresholdValues = {
minValue: 40,
maxValue: 85
};
var width = 600 - margin.left - margin.right;
var height = 270 - margin.top - margin.bottom;
var parseDate = d3.time.format("%d-%b-%y").parse;
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").ticks(5);
var yAxis = d3.svg.axis().scale(y)
.orient("left").ticks(5);
var valueline = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.close);
});
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 = [{
date: "1-May-12",
close: "58.13"
}, {
date: "30-Apr-12",
close: "53.98"
}, {
date: "27-Apr-12",
close: "67.00"
}, {
date: "26-Apr-12",
close: "89.70"
}, {
date: "25-Apr-12",
close: "99.00"
}];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain([0, 100]);
svg.append("path") // Add the valueline path.
.attr("d", valueline(data));
svg.append("g") // Add the X Axis
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g") // Add the Y Axis
.attr("class", "y axis")
.call(yAxis);
svg.selectAll("line.horizontalGrid").data(Object.values(thresholdValues)).enter()
.append("line")
.attr({
"class": "horizontalGrid",
"x1": margin.right,
"x2": width - margin.right,
"y1": function(d) {
if (d != 0) {
return y(d);
}
},
"y2": function(d) {
if (d != 0) {
return y(d);
}
},
"fill": "none",
"shape-rendering": "crispEdges",
"stroke": "grey",
"stroke-width": "2px",
"opacity": 0.4,
"stroke-dasharray": 8
});
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.js"></script>
Js line Chart and i am able to draw chart.While i am using json data I am getting:
Error: Cannot read property 'length' of null(…)
My function is like. i am getting error while parsing data. I am getting json response correctly, but I am enable to draw a chart. Can anyone tell me what is wrong i am doing?
var margin = { top: 30, right: 20, bottom: 30, left: 50 },
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").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(20);
// Define the line
var valueline = d3.svg.line()
.x(function (d) { return x(d.dategraph); })
.y(function (d) { return y(d.assetcount); });
// Adds the svg canvas
var svg = d3.select("linegrapg")
.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 dataset = [{"dategraph":"16-Nov-16","assetcount":299},{"dategraph":"19-Nov-16","assetcount":0},
{"dategraph":"08-Nov-16","assetcount":18},{"dategraph":"14-Nov-16","assetcount":10},
{"dategraph":"17-Nov-16","assetcount":2},{"dategraph":"18-Nov-16","assetcount":0}]
data = JSON.parse(dataset.d);
data.forEach(function (d) {
d.Letter = parseDate(d.dategraph);
d.Freq = +d.assetcount;
});
// Scale the range of the data
x.domain(d3.extent(data, function (d) { return d.Letter; }));
y.domain([0, d3.max(data, function (d) { return d.Freq; })]);
// 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);
}
}
Based on your question, the code runs by commenting out the JSON.parse function call and the two trailing curly braces. The data variable is already an array of objects so there is no need to de-serialize it (from a string type). Other than that, I wasn't able to reproduce the error you were getting. Have a look at the code snippet below.
var margin = {
top: 30,
right: 20,
bottom: 30,
left: 50
},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").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(20);
// Define the line
var valueline = d3.svg.line()
.x(function(d) {
return x(d.dategraph);
})
.y(function(d) {
return y(d.assetcount);
});
// 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 + ")");
var data = [{
"dategraph": "16-Nov-16",
"assetcount": 299
}, {
"dategraph": "19-Nov-16",
"assetcount": 0
}, {
"dategraph": "08-Nov-16",
"assetcount": 18
}, {
"dategraph": "14-Nov-16",
"assetcount": 10
}, {
"dategraph": "17-Nov-16",
"assetcount": 2
}, {
"dategraph": "18-Nov-16",
"assetcount": 0
}];
//var data = JSON.parse(dataset);
data.forEach(function(d) {
d.Letter = parseDate(d.dategraph);
d.Freq = +d.assetcount;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) {
return d.Letter;
}));
y.domain([0, d3.max(data, function(d) {
return d.Freq;
})]);
// 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);
<script src="https://d3js.org/d3.v3.min.js"></script>
My Working Example with tooltip
<!DOCTYPE html>
<meta charset="utf-8">
<style> /* set the CSS */
body { font: 12px Arial;}
path {
stroke: steelblue;
stroke-width: 2;
fill: none;
}
.axis path,
.axis line {
fill: none;
stroke: grey;
stroke-width: 1;
shape-rendering: crispEdges;
}
div.tip {
position: absolute;
text-align: center;
width: auto;
height: auto;
padding: 2px;
font: 12px sans-serif;
background: black;
border: 0px;
border-radius: 8px;
pointer-events: none;
color:white;
border-radius: 8px 8px 8px 8px;
}
</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: 20, bottom: 30, left: 50},
width = 600 - margin.left - margin.right,
height = 270 - margin.top - margin.bottom;
// Parse the date / time
var parseDate = d3.time.format("%d-%b-%y").parse;
var formatTime = d3.time.format("%e %B");
// 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.date); })
.y(function(d) { return y(d.close); });
// Define the div for the tooltip
var div = d3.select("body").append("div")
.attr("class", "tip")
.style("opacity", 0);
// 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 + ")");
// Get the data
var data = [
{"date":"08-Nov-16","close":299},
{"date":"09-Nov-16","close":10},
{"date":"10-Nov-16","close":18},
{"date":"11-Nov-16","close":10},
{"date":"12-Nov-16","close":2},
{"date":"13-Nov-16","close":50}];
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
// Scale the range of the data
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// Add the valueline path.
svg.append("path")
.attr("class", "line")
.attr("d", valueline(data));
// Add the scatterplot
svg.selectAll("dot")
.data(data)
.enter().append("circle")
.attr("r", 5)
.attr("cx", function(d) { return x(d.date); })
.attr("cy", function(d) { return y(d.close); })
.on("mouseover", function(d) {
div.transition()
.duration(200)
.style("opacity", .9);
div .html(formatTime(d.date) + "<br/>" + d.close)
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - 28) + "px");
})
.on("mouseout", function(d) {
div.transition()
.duration(500)
.style("opacity", 0);
});
// 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);
</script>
</body>
I am having issues with my line chart not showing data. I am basing my code off of here. I am using WebStorm and there are no errors in my code or the developer tools in Chrome so I'm at a loss for what is going wrong.
Code:
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatDate = d3.time.format("%d-%b-%y");
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 line = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.users); });
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("lineChart.csv", type, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.users; }));
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");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
function type(d) {
d.date = formatDate.parse(d.date);
d.users = +d.users;
return d;
}
</script>
CSV:
date, users
6-Mar-15,19
11-Mar-15,12
22-Apr-15,22
29-Apr-15,32
3-May-15,1
6-May-15,9
4-Sep-15,2
8-Sep-15,13
10-Sep-15,147
21-Sep-15,4
1-Oct-15,264
4-Oct-15,114
7-Oct-15,63
12-Oct-15,79
The problem is to be found within the header line of your CSV. You have a space character right in front of column header users:
date, users
6-Mar-15,19
d3.csv.parse() will turn this into an attribute d[" users"] containing a space character. Because there is no attribute users in the parsed data's objects, your accessor function type(d) will therefore convert +undefined to NaN and assign this value to d["users"].
This is in compliance with RFC 4180 which states:
2. Definition of the CSV Format
Within the header and each record, there may be one or more
fields, separated by commas. Each line should contain the same
number of fields throughout the file. Spaces are considered part
of a field and should not be ignored. The last field in the
record must not be followed by a comma.
The solution to your problem will be as simple as removing the unwanted space character from your CSV while leaving the rest unchanged:
date,users
6-Mar-15,19
Your code seems to be working fine when using static data. So you should conform the data is loaded correctly inside d3.csv method and converted properly using type function.
Ensure date is parsed and users is an aggregated sum.
EDIT: Try loading csv data as shown below.
d3.csv("lineChart.csv", function(error, data) {
data.forEach(function(d) {
d.date = formatDate.parse(d.date);
d.users = +d.users;
});
---------------------
---------------------
});
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var formatDate = d3.time.format("%d-%b-%y");
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 line = d3.svg.line()
.x(function(d) {
return x(d.date);
})
.y(function(d) {
return y(d.users);
});
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 data = [{
"date": "6-Mar-15",
"users": 19
}, {
"date": "11-Mar-15",
"users": 12
}, {
"date": "22-Apr-15",
"users": 22
}, {
"date": "29-Apr-15",
"users": 32
}, {
"date": "3-May-15",
"users": 1
}, {
"date": "6-May-15",
"users": 9
}, {
"date": "4-Sep-15",
"users": 2
}, {
"date": "8-Sep-15",
"users": 13
}, {
"date": "10-Sep-15",
"users": 147
}, {
"date": "21-Sep-15",
"users": 4
}, {
"date": "1-Oct-15",
"users": 264
}, {
"date": "4-Oct-15",
"users": 114
}, {
"date": "7-Oct-15",
"users": 63
}, {
"date": "12-Oct-15",
"users": 79
}];
data.forEach(function(d) {
d.date = formatDate.parse(d.date);
d.users = +d.users;
});
alert(JSON.stringify(data));
x.domain(d3.extent(data, function(d) {
return d.date;
}));
y.domain(d3.extent(data, function(d) {
return d.users;
}));
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(data)
.attr("class", "line")
.attr("d", line);
body {
font: 10px sans-serif;
}
.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;
}
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
I want to filter my key value pair array into two sets and draw a line chart for each sets. I used underscore.js to filter the data. I am using d3.js to draw the line chart. When I add spectrum1Data as data object in D3 it doesn't draw the line chart - Can someone look at the below code and let me know what I am missing?
my data is like as below
spectrum_data = [
{
"SpectrumName": "Spectrum1",
"Mass": "27.19",
"Intensity": "20.2"
},
{
"SpectrumName": "Spectrum1",
"Mass": "11.39",
"Intensity": "10.7"
},
{
"SpectrumName": "Spectrum2",
"key": "value",
"Intensity": "12.9"
},
{
"SpectrumName": "Spectrum2",
"Mass": "21.83",
"Intensity": "30.9"
}];
The underscore JS function to filter data for spectrum 1 is as below.
var spectrum1Data = _(spectrum_data).chain()
.filter(function(x){ return x.SpectrumName=="Spectrum1"}).value()[0];
The d3.js function to draw a line is as below
var line = d3.svg.line()
.interpolate("cardinal")
.x(function(d) {//console.log(xScale(parseInt(d.Mass)));
return xScale(d.Mass); })
.y(function(d) {//console.log(xScale(d.Intensity));
return yScale(d.Intensity); });
focus.append("path")
.datum(spectrum1Data)
.attr("class", "line")
.attr("d", line)
<!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>
<script src="http://d3js.org/d3.v3.js"></script>
<script>
var spectrum_data = [
{
"SpectrumName": "Spectrum1",
"Mass": "27.19",
"Intensity": "20.2"
},
{
"SpectrumName": "Spectrum1",
"Mass": "11.39",
"Intensity": "10.7"
},
{
"SpectrumName": "Spectrum2",
"Mass": "30",
"Intensity": "12.9"
},
{
"SpectrumName": "Spectrum2",
"Mass": "21.83",
"Intensity": "30.9"
}];
var margin = {top: 20, right: 80, bottom: 30, left: 50},
width = 900 - 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 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("cardinal")
.x(function(d) { return x(d.Intensity); })
.y(function(d) { return y(d.Mass); });
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 + ")");
color.domain(d3.keys(spectrum_data[0]).filter(function(key) { return key == "SpectrumName"; }));
//filter data based on spectrumname
var nested_data = d3.nest().key(function(d) { return d.SpectrumName; }).entries(spectrum_data);
console.log(nested_data);
x.domain([d3.min(nested_data, function(d) { return d3.min(d.values, function (d) { return d.Intensity; }); }),
d3.max(nested_data, function(d) { return d3.max(d.values, function (d) { return d.Intensity; }); })]);
y.domain([0, d3.max(nested_data, function(d) { return d3.max(d.values, function (d) { return d.Mass; }); })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
var Spectrum = svg.selectAll(".spectrum")
.data(nested_data, function(d) { return d.key; })
.enter().append("g")
.attr("class", "spectrum");
Spectrum.append("path")
.attr("class", "line")
.attr("d", function(d) { return line(d.values); })
.style("stroke", function(d) { return color(d.key); });
</script>
Instead of using underscore.js ,you can use the d3.nest() of d3.js for filtering. This is the code with your data drawing line chart.