D3 graph not displaying JSON information from variable - json

Instead of loading data from a CSV file, I would like to load JSON data from a variable.
let jsonData = [
{"Date": "1/1/2014 01:00", "Air_Temp": 3.1},
{"Date": "1/1/2014 02:00", "Air_Temp": 3.2},
{"Date": "1/1/2014 03:00", "Air_Temp": 1.6},
{"Date": "1/1/2014 04:00", "Air_Temp": 1.0},
{"Date": "1/1/2014 05:00", "Air_Temp": 2.3}
];
The graph is being displayed with no errors logged to the console, but the data is not being loaded.
https://jsfiddle.net/s9cbwvL1/1/

Fyi
you are not using your own created function
parseDate function and type function
when i read that function, i think somebody manage to rearange the d.Date on the data
result
your axis domain is [ invalid date, invalid date ]
solution
i convert d.Date to proper format
you sending data on each item not in array
result
your chart not drawing nor having error
solution
i make it double array on jsonData
Line_chart.data([jsonData])
context.data([jsonData])
take a look
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;
}
.zoom {
cursor: move;
fill: none;
pointer-events: all;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script type="text/javascript">
//Example: https://bl.ocks.org/EfratVil/92f894ac0ba265192411e73f633a3e2f
let jsonData1 =
[
{"Date": "1/1/2014 01:00", "Air_Temp": 3.1},
{"Date": "1/1/2014 02:00", "Air_Temp": 3.2},
{"Date": "1/1/2014 03:00", "Air_Temp": 1.6},
{"Date": "1/1/2014 04:00", "Air_Temp": 1.0},
{"Date": "1/1/2014 05:00", "Air_Temp": 2.3}
];
var svg = d3.select("svg"),
margin = {top: 20, right: 20, bottom: 110, left: 40},
margin2 = {top: 430, right: 20, bottom: 30, left: 40},
width = +svg.attr("width") - margin.left - margin.right,
height = +svg.attr("height") - margin.top - margin.bottom,
height2 = +svg.attr("height") - margin2.top - margin2.bottom;
var parseDate = d3.timeParse("%m/%d/%Y %H:%M");
let jsonData = jsonData1.map(function(d,i){ d.Date = parseDate(d.Date); return d })
var x = d3.scaleTime().range([0, width]),
x2 = d3.scaleTime().range([0, width]),
y = d3.scaleLinear().range([height, 0]),
y2 = d3.scaleLinear().range([height2, 0]);
var xAxis = d3.axisBottom(x),
xAxis2 = d3.axisBottom(x2),
yAxis = d3.axisLeft(y);
var brush = d3.brushX()
.extent([[0, 0], [width, height2]])
.on("brush end", brushed);
var zoom = d3.zoom()
.scaleExtent([1, Infinity])
.translateExtent([[0, 0], [width, height]])
.extent([[0, 0], [width, height]])
.on("zoom", zoomed);
var line = d3.line()
.x(function (d) { return x(d.Date); })
.y(function (d) { return y(d.Air_Temp); });
var line2 = d3.line()
.x(function (d) { return x2(d.Date); })
.y(function (d) { return y2(d.Air_Temp); });
var clip = svg.append("defs").append("svg:clipPath")
.attr("id", "clip")
.append("svg:rect")
.attr("width", width)
.attr("height", height)
.attr("x", 0)
.attr("y", 0);
var Line_chart = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.attr("clip-path", "url(#clip)");
var focus = svg.append("g")
.attr("class", "focus")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
var context = svg.append("g")
.attr("class", "context")
.attr("transform", "translate(" + margin2.left + "," + margin2.top + ")");
x.domain(d3.extent(jsonData, function(d) { return d.Date; }));
y.domain([0, d3.max(jsonData, function (d) { return d.Air_Temp; })]);
x2.domain(x.domain());
y2.domain(y.domain());
focus.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
focus.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
Line_chart.selectAll('path')
.data([jsonData])
.enter()
.append("path")
.attr("class", "line")
.attr("d", function (d){ line });
context.append("path")
.data([jsonData])
.attr("class", "line")
.attr("d", line2);
context.append("g")
.attr("class", "axis axis--x")
.attr("transform", "translate(0," + height2 + ")")
.call(xAxis2);
context.append("g")
.attr("class", "brush")
.call(brush)
.call(brush.move, x.range());
svg.append("rect")
.attr("class", "zoom")
.attr("width", width)
.attr("height", height)
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom);
function brushed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "zoom") return; // ignore brush-by-zoom
var s = d3.event.selection || x2.range();
x.domain(s.map(x2.invert, x2));
Line_chart.select(".line").attr("d", line);
focus.select(".axis--x").call(xAxis);
svg.select(".zoom").call(zoom.transform, d3.zoomIdentity
.scale(width / (s[1] - s[0]))
.translate(-s[0], 0));
}
function zoomed() {
if (d3.event.sourceEvent && d3.event.sourceEvent.type === "brush") return; // ignore zoom-by-brush
var t = d3.event.transform;
x.domain(t.rescaleX(x2).domain());
Line_chart.select(".line").attr("d", line);
focus.select(".axis--x").call(xAxis);
context.select(".brush").call(brush.move, x.range().map(t.invertX, t));
}
function type(d) {
d.Date = parseDate(d.Date);
d.Air_Temp = +d.Air_Temp;
return d;
}
</script>
</body>
</html>

You need to convert the dates
var parseDate = d3.timeParse("%m/%d/%Y %H:%M");
jsonData.forEach( d => { d.Date = parseDate(d.Date); });
And pass the dataset as one to the path elements
Line_chart.append("path")
.data([jsonData])
.attr("class", "line")
.attr("d", line);
context.append("path")
.data([jsonData])
.attr("class", "line")
.attr("d", line2);

Related

Create a Vertical Column Chart with D3 using CSV with Similar String Occurrences

I am seeking assistance with my script in creating a column chart with similar string occurrences listed in a CSV file. I am creating this chart using D3.js V3. The script and technique I’m using to capture the length of the items return results, but the number count of the length is not close to the actual count, very short from the expect item count. Can someone please review my script and see what is causing my length count to be way off from the actual number count. Any help, suggestion, or techniques will be greatly appreciated.
Below is a sample of the CSV file concept and D3 script. Thank you in advance.
d3.csv("../../data/teamData.csv", function(error, csv_data) {
if (error){
alert("Data didn't load, Refresh your browser");
}else{
for (var i = 0; i < csv_data.length; i++) {
if(csv_data[i].Team == "Team 1"){
team1 = csv_data[i].Team;
}
if(csv_data[i].Team == "Team 2"){
team2 = csv_data[i].Team;
}
}
}
var teamCount1 = team1.length;
var teamCount2 = team2.length;
console.log(teamCount1);//Not showing correct number count
console.log(teamCount2);//Not showing correct number count
var margin = {top: 2, right: 2, bottom: 60, left: 2},
w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
var barPadding = 1;
var chartdata = [teamCount1, teamCount2];
var textData = ['Team 1', 'Team 2'];
var xScale = d3.scale.ordinal()
.domain(d3.range(chartdata2.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(chartdata)])
.range([0, h]);
var svg = d3.select(".chartData")
.append("svg")
.attr("preserveAspectRatio", "xMidYMin")
.attr("viewBox", "0 0 1000 650")
.attr("width", "100%")
.attr("height", "100%")
.attr("display",'block')
.append("g").attr("class","stackChart2")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Create bars
svg.selectAll("barRect")
.data(chartdata)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", function(d) {
return "rgb(0, 0, " + (d * 10) + ")";
})
.on("click", function() {
sortBars();
});
//Create labels
svg.selectAll("text")
.data(chartdata)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) - 10;
})
.attr("font-family", "sans-serif")
.attr("font-size", "14px")
.attr("fill", "black");
//Text Label
var yTextPadding = 20;
svg.selectAll(".bartext2")
.data(textData)
.enter()
.append("text")
.attr("class", "bartext2")
.attr("text-anchor", "middle")
.attr("fill", "black")
.attr("font-family", "sans-serif")
.style("font-size", "16px")
.attr("x", function(d,i) {return xScale(i)+xScale.rangeBand()/2;})
.attr("y", 460)
.text(function(d){return d;});
//Define sort order flag
var sortOrder = false;
//Define sort function
var sortBars = function() {
//Flip value of sortOrder
sortOrder = !sortOrder;
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.ascending(a, b);
} else {
return d3.descending(a, b);
}
})
.transition()
.delay(function(d, i) {
return i * 50;
})
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
});
}
});//End of D3 function
I was able to figure it out referencing this stackoverflow post: D3 Loading in CSV file then using only specific columns. I was able to filter out the needed column from my CSV file which was "Team", using d3 map as follow; var col2data = csv_data.map(function(d) { return d.Team });
Then I followed this stackoverflow post to filter my specific reoccurring item from the "Team" column: d3.js filter from csv file using multiple columns. This post made it possible to get the length of the items to build my column chart. All is working as expected. Below is the edited script. I hope this will help someone in the future encountering this issue.
d3.csv("../../data/teamData.csv", function(csv_data) {
//Filter CSV File to Specific Column
var col2data = csv_data.map(function(d) { return d.Team });
console.log(col2data);
//Filter CSV Column for Specific Column Item
var team1 = csv_data.filter(function(d){
if( d["Team"] == "Team 1"){
return d;
}
})
var team2 = csv_data.filter(function(d){
if( d["Team"] == "Team 2"){
return d;
}
})
console.log(team1);
var teamCount1 = team1.length;
var teamCount2 = team2.length;
//console.log(teamCount1);//Not showing correct number count
//console.log(teamCount2);//Not showing correct number count
var margin = {top: 2, right: 2, bottom: 60, left: 2},
w = 960 - margin.left - margin.right,
h = 500 - margin.top - margin.bottom;
var barPadding = 1;
var chartdata = [teamCount1, teamCount2];
var textData = ['Team 1', 'Team 2'];
var xScale = d3.scale.ordinal()
.domain(d3.range(chartdata.length))
.rangeRoundBands([0, w], 0.05);
var yScale = d3.scale.linear()
.domain([0, d3.max(chartdata)])
.range([0, h]);
var svg = d3.select(".plot-div")
.append("svg")
.attr("preserveAspectRatio", "xMidYMin")
.attr("viewBox", "0 0 1000 650")
.attr("width", "100%")
.attr("height", "100%")
.attr("display",'block')
.append("g").attr("class","stackChart2")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
//Create bars
svg.selectAll("barRect")
.data(chartdata)
.enter()
.append("rect")
.attr("x", function(d, i) {
return xScale(i);
})
.attr("y", function(d) {
return h - yScale(d);
})
.attr("width", xScale.rangeBand())
.attr("height", function(d) {
return yScale(d);
})
.attr("fill", function(d) {
return "rgb(0, 0, " + (d * 10) + ")";
})
.on("click", function() {
sortBars();
});
//Create labels
svg.selectAll("text")
.data(chartdata)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("text-anchor", "middle")
.attr("x", function(d, i) {
return xScale(i) + xScale.rangeBand() / 2;
})
.attr("y", function(d) {
return h - yScale(d) - 10;
})
.attr("font-family", "sans-serif")
.attr("font-size", "14px")
.attr("fill", "black");
//Text Label
var yTextPadding = 20;
svg.selectAll(".bartext2")
.data(textData)
.enter()
.append("text")
.attr("class", "bartext2")
.attr("text-anchor", "middle")
.attr("fill", "black")
.attr("font-family", "sans-serif")
.style("font-size", "16px")
.attr("x", function(d,i) {return xScale(i)+xScale.rangeBand()/2;})
.attr("y", 460)
.text(function(d){return d;});
//Define sort order flag
var sortOrder = false;
//Define sort function
var sortBars = function() {
//Flip value of sortOrder
sortOrder = !sortOrder;
svg.selectAll("rect")
.sort(function(a, b) {
if (sortOrder) {
return d3.ascending(a, b);
} else {
return d3.descending(a, b);
}
})
.transition()
.delay(function(d, i) {
return i * 50;
})
.duration(1000)
.attr("x", function(d, i) {
return xScale(i);
});
}
});//End of D3 function

d3 v4 padding inner set to .001 doesn't actually result in small padding between ranges

Is there a way to minimize the padding between ranges in a grouped horizontal bar chart?
I am building a horizontal bar chart directive for AngularJS and at the moment I am pretty close but it's the spacing that I am not exactly happy with. If there is a better way to build the vertical ranges I would very much appreciate any tips. Here's my result so far:
angular.module('MissionControlApp').directive('d3GroupedHorizontalBarChart2', ['d3', '$timeout', function(d3, $timeout) {
return {
restrict: 'E',
scope: {
data: '=',
onClick: '&d3OnClick'
},
link: function(scope, ele) {
var refreshScope = function() {
scope.$apply();
};
var svg = d3.select(ele[0])
.append("svg")
.attr("width", "100%");
// on window resize, re-render d3 canvas
window.onresize = function() {
return scope.$apply();
};
scope.$watch(function(){
return angular.element(window)[0].innerWidth;
}, function(){
return scope.render(scope.data);
}
);
// watch for data changes and re-render
scope.$watch("data", function(newVals) {
if(!newVals) return;
return scope.render(newVals);
}, true);
// define render function for grouped bar charts
scope.render = function(data){
if(!data) return;
// remove all previous items before render
svg.selectAll("*").remove();
// setup variables
var margin = {top: 25, right: 40, bottom: 70, left: 150};
var width = d3.select(ele[0])._groups[0][0].offsetWidth - margin.left - margin.right;
var height = (scope.data.length * 60);
svg.attr('height', height + margin.top + margin.bottom);
var y0 = d3.scaleBand()
.rangeRound([0, height])
.paddingInner(0.01);
var y1 = d3.scaleBand()
.padding(0.01);
var x = d3.scaleLinear()
.rangeRound([0, width]);
var color = d3.scaleLinear()
.domain([0, 25, 50, 75, 100])
.range(["#51b75d", "#90eb9d","#ffff8c","#f5c93f","#c45c44"])
.interpolate(d3.interpolateHcl);
var xAxis = d3.axisBottom(x)
.tickSizeInner(-(height-5))
.tickPadding(8);
var keys = d3.keys(data[0]).filter(function(key) { return key !== "user"; });
y0.domain(data.map(function(d) { return d.user; }));
y1.domain(keys).rangeRound([0, y0.bandwidth()]);
x.domain([0, 100]);
// Define bars
var bar = svg.selectAll(".bar")
.data(data)
.enter().append("g")
.attr("transform", function(d) { return "translate(" + margin.left + "," + (y0(d.user) + (y0.bandwidth()/2) + margin.top - y1.bandwidth()) + ")"; });
var barEnter = bar.selectAll("rect")
.data(function(d) { return d.values; })
.enter();
barEnter.append("rect")
.attr("height", y1.bandwidth())
.attr("y", function(d) {return y1(d.name); })
.attr("x", 0)
.attr("value", function(d){return d.name;})
.attr("width", 0)
.attr("fill", function(d) { return color(d.value); })
.on("mouseover", function() { d3.select(this).style("cursor", "pointer");})
.on("mouseout", function() { d3.select(this).style("cursor", "default");})
.on("click", function(d){
scope.onClick({item: d});
d3.select(".selectedBlueFill").classed("selectedBlueFill", false);
d3.select(this).classed("selectedBlueFill", true);
$timeout(refreshScope, 0, false); // flush the digest cycle
})
.transition()
.duration(1000)
.attr("width", function(d) { return x(d.value); });
barEnter.append("text")
.attr("fill", "#000")
.attr("y", function(d){return y1(d.name) + (y1.bandwidth() / 2);})
.attr("x", function(d){return x(d.value);})
.attr("dx", 5)
.attr("dy", ".35em")
.text(function(d){return parseFloat(d.value).toFixed(0) + "%";})
.attr("fill-opacity", 0)
.transition()
.duration(1500)
.attr("fill-opacity", 1);
// Set up x axis
svg.append("g")
.attr("class", "axisHorizontal")
.attr("transform", "translate(" + margin.left + "," + (height + margin.top) + ")")
.call(xAxis);
// Set up y axis
svg.append("g")
.attr("class", "y axis")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(d3.axisLeft(y0));
// Draw the legend
// Create the gradient for the legend
svg.append("defs")
.append("linearGradient")
.attr("id", "legend-traffic")
.attr("x1", "0%").attr("y1", "0%")
.attr("x2", "100%").attr("y2", "0%")
.selectAll("stop")
.data(color.range())
.enter().append("stop")
.attr("offset", function(d,i) { return i/(color.range().length-1); })
.attr("stop-color", function(d) { return d; });
// Legend variables
var legendWidth = width * 0.6;
var legendHeight = 10;
// Legend container
var legendSvg = svg.append('g')
.attr("class", "legendWrapper")
.attr("transform", "translate(" + ((width + margin.left + margin.right)/2) + "," + (height + margin.top + margin.bottom) + ")");
// Draw the rectangle
legendSvg.append("rect")
.attr("class", "legendRect")
.attr("x", -legendWidth/2)
.attr("y", -30)
.attr("width", legendWidth)
.attr("height", legendHeight)
.attr("fill", "url(#legend-traffic)");
// Append title
legendSvg.append("text")
.attr("class", "legendTitle")
.attr("x", 0)
.attr("y", -35)
.attr("text-anchor", "middle")
.text("Worksets Opened %");
// Set scale for x-axis
var xScale = d3.scaleLinear()
.range([0, legendWidth])
.domain([0,100]);
// Define x-axis
var legendAxis = d3.axisBottom(xScale).ticks(5);
// Set up x-axis
legendSvg.append("g")
.attr("class", "axisLegend")
.attr("transform", "translate(" + (-legendWidth/2) + "," + (legendHeight-30) + ")")
.call(legendAxis);
};
}
};
}]);
However the result I am getting is with large inner spacing. I am setting the .paddingInner property to 0.001 and still pretty much end up with large spacing......ideas?
The idea would be to make groups, where each group hold unique bars for the group.
Now once you have the group you can alter the between distance with some maths, as shown below in snippet below:
var bar = chart
.selectAll("g")
.data(zippedData)
.enter().append("g")
.attr("transform", function(d, i) {
//here barHeight is the width of the bars.
return "translate(" + spaceForLabels + ","
+ (i * barHeight + gapBetweenGroups * (0.5 + Math.floor(i/data.series.length))) + ")";
});
By changing value of gapBetweenGroups you can regulate the distance of the groups.
Working code here

d3js json pie chart

I am trying to create a piechart for some data I have in a JSON file, however I keep getting an error and I am not sure why.
My JSON file is like this:
{"data":[
{"ap": [
{"floorratio": [
{"floor":"Basement", "ratio": 0.20},
{"floor":"Ground", "ratio": 0.20},
{"floor":"First Floor", "ratio": 0.15},
{"floor":"Second Floor", "ratio": 0.20},
{"floor":"Third Floor", "ratio": 0.25}
]}
]},
{"ap": [
{"floorratio": [
{"floor":"Basement", "ratio": 0.10},
{"floor":"Ground", "ratio": 0.30},
{"floor":"First Floor", "ratio": 0.10},
{"floor":"Second Floor", "ratio": 0.15},
{"floor":"Third Floor", "ratio": 0.35}
]}
]}
]}
and my HTML code is:
<!doctype html>
<html>
<head>
<title>Pie Chart Test</title>
<script src="d3.min.js"></script>
</head>
<style>
body {
font: 10px sans-serif;
}
.arc path {
stroke: #fff;
}
</style>
<body>
<script>
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
var pie = d3.layout.pie()
.sort(null)
.value(function (d) {
return d.data[0].ap[0].floorratio[0].ratio;
});
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("APCategories.json", function (data) {
var g = svg.selectAll(".arc")
.data(pie(function (d) { return d.data[0].ap[0].floorratio[0]}))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function (d) {
return color[d.data[0].ap[0].floorratio[0].floor];
});
g.append("text")
.attr("transform", function (d) {
return "translate(" + arc.centroid(d) + ")";
})
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function (d) {
return d.data[0].ap[0].floorratio[0].floor;
});
});
</script>
</body>
</html>
I keep getting the error when I inspect the element that i.map is not a function. Am I reading the data into the code incorrectly? Any help would be appreciated.
edit: I am currently only trying to load the first ap, the json file will be much bigger and I will be creating a pie chart that changes so that it represents each ap.floorratio.
So for now, only the data from the first floorratio array needs to go into the pie chart.
Here's a working version.
var width = 960,
height = 500,
radius = Math.min(width, height) / 2;
var color = d3.scale.ordinal()
.range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);
var arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(0);
// defines wedge size
var pie = d3.layout.pie()
.sort(null)
.value(function (d) { return d.ratio; });
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
.attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
d3.json("APCategories.json", function(error, data) {
node = data.data[0].ap[0].floorratio; // <------ here
var g = svg.selectAll(".arc")
.data(pie(node))
.enter().append("g")
.attr("class", "arc");
g.append("path")
.attr("d", arc)
.style("fill", function(d) { return color(d.data.floor); });
g.append("text")
.attr("transform", function (d) { return "translate(" + arc.centroid(d) + ")"; })
.attr("dy", ".35em")
.style("text-anchor", "middle")
.text(function (d) { return d.data.floor; });
});
The [0] after floorratio wasn't necessary.
http://bl.ocks.org/steveharoz/0638d230c133da1de385

How To Filter Data by Date Range on D3.js Line Chart?

I've managed to create a simple line chart using data from a csv file but I only want to display data from the last 7 days, how do I do this?
I believe I need to do a .filter somewhere but I can't find any good examples, I believe it needs to go in this block :
// Get the data
d3.csv("CSVdata.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
console.log("Date : " + d.date);
d.close = +d.close;
});
I've uploaded the chart which can be viewed here :
http://plnkr.co/edit/JyQS0X?p=preview
The html I'm using is :
<!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;
}
</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/%m/%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(5);
// 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 + ")");
// Get the data
d3.csv("CSVdata.csv", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
console.log("Date : " + 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 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>
The data.csv file I'm using is
date,close
18/06/2015,49582.51
18/06/2015,50582.51
18/06/2015,52582.51
17/06/2015,52782.51
15/06/2015,55313.51
10/06/2015,58110.51
10/06/2015,55778.02
1/06/2015,53289.42
27/05/2015,53288.25
27/05/2015,50955.76
25/05/2015,48467.16
22/05/2015,49467.16
20/05/2015,49557.78
14/05/2015,50557.78
13/05/2015,53354.78
13/05/2015,50866.18
11/05/2015,48533.69
29/04/2015,49533.69
29/04/2015,47201.2
25/04/2015,44712.6
25/04/2015,45061.21
22/04/2015,45717.21
15/04/2015,45807.83
15/04/2015,43525.88
14/04/2015,41037.28
14/04/2015,42114.39
14/04/2015,42285.39
14/04/2015,43783.74
13/04/2015,46580.74
1/04/2015,48580.74
1/04/2015,46334.49
23/03/2015,43845.89
18/03/2015,43936.51
18/03/2015,41690.26
16/03/2015,39201.66
4/03/2015,41998.66
4/03/2015,39510.06
1/03/2015,37263.82
27/02/2015,37263.04
23/02/2015,37213.04
18/02/2015,34765.06
17/02/2015,32518.81
16/02/2015,30598.55
14/02/2015,33395.55
13/02/2015,36192.55
13/02/2015,36170.45
6/02/2015,36120.45
4/02/2015,36070.45
4/02/2015,33581.85
30/01/2015,31335.61
28/01/2015,31285.61
23/01/2015,21285.61
22/01/2015,21235.61
16/01/2015,21326.23
16/01/2015,21276.23
15/01/2015,21226.23
15/01/2015,18262.24
14/01/2015,10534.4
13/01/2015,10244.35
13/01/2015,12243.98
13/01/2015,92766.86
13/01/2015,82766.86
13/01/2015,42766.86
9/01/2015,22766.86
9/01/2015,22716.86
4/01/2015,22666.86
3/01/2015,22722.5
2/01/2015,22763.34
2/01/2015,22713.34
31/12/2014,22663.34
29/12/2014,22731.42
26/12/2014,22831.35
26/12/2014,22781.35
19/12/2014,22731.35
19/12/2014,22681.35
12/12/2014,22631.35
12/12/2014,22581.35
6/12/2014,22531.35
5/12/2014,22570.01
5/12/2014,22520.01
3/12/2014,22470.01
1/12/2014,51470.01
30/11/2014,51469.27
30/11/2014,51497.85
28/11/2014,51509.87
28/11/2014,51459.87
22/11/2014,51409.87
22/11/2014,51450.48
21/11/2014,51483.94
21/11/2014,1483.94
21/11/2014,1433.94
19/11/2014,1383.94
17/11/2014,1412.85
16/11/2014,1443.89
14/11/2014,1484.3
14/11/2014,1434.3
12/11/2014,1384.3
10/11/2014,1422.1
7/11/2014,1458.79
7/11/2014,1408.79
5/11/2014,1358.79
4/11/2014,1436.29
4/11/2014,1469.04
3/11/2014,1502.16
31/10/2014,1517.32
31/10/2014,1467.32
25/10/2014,1417.32
25/10/2014,1510.72
24/10/2014,1534.88
24/10/2014,1694.15
24/10/2014,1644.15
19/10/2014,1594.15
17/10/2014,1653.95
17/10/2014,1603.95
15/10/2014,1553.95
15/10/2014,1640.95
14/10/2014,1703.89
12/10/2014,1805.26
12/10/2014,1843.98
10/10/2014,1887.85
10/10/2014,1837.85
3/10/2014,1787.85
3/10/2014,1737.85
28/09/2014,1687.85
26/09/2014,1701.06
26/09/2014,1651.06
23/09/2014,1601.06
19/09/2014,1644.2
19/09/2014,1594.2
12/09/2014,1544.2
12/09/2014,1494.2
9/09/2014,1444.2
8/09/2014,1461.94
7/09/2014,1470.36
7/09/2014,1476.36
5/09/2014,1501.31
5/09/2014,1451.31
4/09/2014,1401.31
3/09/2014,1424.39
1/09/2014,1440.7
29/08/2014,1440.67
29/08/2014,1390.67
25/08/2014,1340.67
23/08/2014,1385.45
22/08/2014,1420.43
22/08/2014,1370.43
18/08/2014,1320.43
16/08/2014,1333.78
15/08/2014,1428.61
15/08/2014,1440.6
15/08/2014,1390.6
8/08/2014,1340.6
8/08/2014,1290.6
5/08/2014,1240.6
1/08/2014,1285.13
1/08/2014,1235.13
28/07/2014,1185.13
25/07/2014,1213.18
25/07/2014,1231.79
25/07/2014,1181.79
24/07/2014,1131.79
23/07/2014,1285.79
22/07/2014,1306.14
21/07/2014,1339.94
19/07/2014,1385.34
18/07/2014,1416.01
18/07/2014,1366.01
16/07/2014,1316.01
12/07/2014,1322.46
11/07/2014,1338.7
11/07/2014,1288.7
10/07/2014,1238.7
7/07/2014,1255.35
6/07/2014,1278.32
4/07/2014,1311.12
4/07/2014,1261.12
30/06/2014,1211.12
27/06/2014,1225.01
27/06/2014,1175.01
25/06/2014,1125.01
24/06/2014,1147.16
23/06/2014,1177.32
23/06/2014,1183.48
20/06/2014,1201.65
20/06/2014,1151.65
19/06/2014,1101.65
18/06/2014,1123.15
14/06/2014,1134.29
13/06/2014,1169.81
13/06/2014,1119.81
12/06/2014,1069.81
11/06/2014,1092.19
6/06/2014,1121.74
6/06/2014,1071.74
5/06/2014,1021.74
2/06/2014,1075.03
1/06/2014,1095.2
1/06/2014,1136.1
30/05/2014,1136.07
30/05/2014,1086.07
You can use the filter function (plain JavaScript)
After your data.forEach block
var cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - 90);
data = data.filter(function(d) {
return d.date > cutoffDate;
})
Adjust 90 to 7 or (max - 7) as necessary
Plunk - http://plnkr.co/edit/nnRslY8jcuMpMRDmGP4B?p=preview

How can I use d3.layout.stack with this code to draw a line chart using D3.js?

I'm trying to draw a Area chart . I couldn't access to the data and I don't know WHY . In the firefox console " data is not defined". This is my code and data .
This data which is JSON format is located on the server side :
{"Id":466,"Name":"korea",
"Occurrences":[
{"OccurrenceDate":"\/Date(1398207600000+0100)\/","OccurrenceFrequency":27},
{"OccurrenceDate":"\/Date(1398726000000+0100)\/","OccurrenceFrequency":1},
{"OccurrenceDate":"\/Date(1398898800000+0100)\/","OccurrenceFrequency":4},
{"OccurrenceDate":"\/Date(1399071600000+0100)\/","OccurrenceFrequency":303}
]
}
This is my code
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
var margin = {top: 80, right: 80, bottom: 80, left: 80},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var parseDate1 = d3.time.format.iso.parse;
// Scales and axes. Note the inverted domain for the y-scale: bigger is up!
var x = d3.time.scale().range([0, width]),
y = d3.scale.linear().range([height, 0]),
xAxis = d3.svg.axis().scale(x).tickSize(-height).tickSubdivide(true),
yAxis = d3.svg.axis().scale(y).ticks(4).orient("right");
// An area generator, for the light fill.
var area = d3.svg.area()
.interpolate("monotone")
.x(function(d) { return x(d.OccurrenceDate); })
.y0(height)
.y1(function(d) { return y(d.OccurrenceFrequency); });
// A line generator, for the dark stroke.
var line = d3.svg.line()
.interpolate("monotone")
.x(function(d) { return x(d.OccurrenceDate); })
.y(function(d) { return y(d.OccurrenceFrequency); });
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 strURI = "http://tr-l6/STWebService/Service.svc/session/Fetchnodehistorybyname?
strnodename=korea";
// use jquery to get the json dataset because I cannot get d3.json to work with Firefox/Chrome (but it is OK with IE)
// this is probably a jsonp / cross domain issue that requires further tweaking in the WCF web,config file
// d3.json(strURI,function(error, graph) {
$.ajax({
type: "GET",
url: strURI,
dataType: 'jsonp',
success: function (graph) {
x
data.forEach(function(d) {
// Convert unix date format to regular format
var dc
//dc = (d.date).substring(1, 26);
dc = d.OccurrenceDate.substring(6, 16)
console.log(dc);
dc = new Date(dc*1000)
console.log(dc);
d.OccurrenceDate= parseDate1(dc);
d.OccurrenceFrequency = +d.OccurrenceFrequency;
return d
});
x.domain(d3.extent(data, function(d) { return d.OccurrenceDate; }));
y.domain([0, d3.max(data, function(d) { return d.OccurrenceFrequency; })]);
svg.append("path")
.datum(data)
.attr("class", "area")
.attr("d", area);
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")
}});
I dont know if it is the reason for the Error but you missed the </script> Script at the End