D3 Update Graph - javascript

really stucked on this issue for days. I am trying to update my d3 graph to show how long it takes to run a function on a calculator. With the info I get, I will show the time taken and display it on the graph that I previously drew. My issue here now is that I just can't get the graph to update.
Codes for the graph:
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 400 - margin.left - margin.right,
height = 300 - 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()
.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 + ")");
var data = dataone.map(function(d) {
return {
date:d[0],
close: d[1]
};
});
console.log(data);
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
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("Price ($)");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
Code for update function and update of array:
function updateArray(){
dataone.push(clickss-0.5,clickss);
updateData();
}
function updateData() {
var data = dataone.map(function(d) {
return {
date:d[0],
close: d[1]
};
});
// Scale the range of the data again
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain([0, d3.max(data, function(d) { return d.close; })]);
// Select the section we want to apply our changes to
var svg = d3.select("body").transition();
// Make the changes
svg.select(".line") // change the line
.duration(750)
.attr("d", valueline(data));
svg.select(".x.axis") // change the x axis
.duration(750)
.call(xAxis);
svg.select(".y.axis") // change the y axis
.duration(750)
.call(yAxis);
}
Please advise on how I can get this to work. I read quite a few guides now but

Couple things:
1.) In your update function, your line generator function is line not valueline.
2.) By looking at your accessor functions, I don't think you meant dataone.push(clickss-0.5,clickss); but rather dataone.push([clickss-0.5,clickss]);. You need an array of arrays.
In addition, you don't need to map your dataone array to another structure. Just change your accessors:
x.domain(d3.extent(data, function(d) {
return d[0];
}));
y.domain(d3.extent(data, function(d) {
return d[1];
}));
...
var line = d3.svg.line()
.x(function(d) {
return x(d[0]);
})
.y(function(d) {
return y(d[1]);
});
Here's your code working and cleaned up a bit:
<!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 dataone = [];
for (var i = 0; i < 10; i++){
dataone.push([i,Math.random()]);
}
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 50
},
width = 400 - margin.left - margin.right,
height = 300 - 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()
.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 + ")");
// Scale the range of the data again
x.domain(d3.extent(dataone, function(d) {
return d[0];
}));
y.domain([0, d3.max(dataone, function(d) {
return d[1];
})]);
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("Price ($)");
svg.append("path")
.datum(dataone)
.attr("class", "line")
.attr("d", line)
.style("fill","none")
.style("stroke","steelblue");
function updateData() {
// Scale the range of the data again
x.domain(d3.extent(dataone, function(d) {
return d[0];
}));
y.domain([0, d3.max(dataone, function(d) {
return d[1];
})]);
// Select the section we want to apply our changes to
var svg = d3.select("body").transition();
// Make the changes
svg.select(".line") // change the line
.duration(750)
.attr("d", line(dataone));
svg.select(".x.axis") // change the x axis
.duration(750)
.call(xAxis);
svg.select(".y.axis") // change the y axis
.duration(750)
.call(yAxis);
}
setInterval(function(){
for (var i = 0; i < 5; i++){
dataone.push([dataone.length + i, Math.random()]);
}
updateData();
},1000);
</script>
</body>
</html>

Related

d3 - how to add x-axis labels for only years on a monthly chart?

I'm creating a bar chart in d3 (using r2d3 in R) that shows data per month. I'm wondering how I can format the x-axis so that while there is a bar for each month, the labels only show the year markers (i.e. under each january bar.)
Data look like this:
letter,frequency
1/1/2017,144
2/1/2017,85
3/1/2017,59
4/1/2017,73
5/1/2017,68
6/1/2017,91
7/1/2017,107
8/1/2017,94
9/1/2017,79
10/1/2017,84
11/1/2017,70
12/1/2017,86
1/1/2018,72
2/1/2018,71
3/1/2018,82
4/1/2018,50
5/1/2018,86
6/1/2018,75
7/1/2018,62
8/1/2018,72
9/1/2018,65
10/1/2018,75
11/1/2018,63
12/1/2018,87
1/1/2019,59
2/1/2019,60
3/1/2019,99
4/1/2019,81
Data in console:
D3 Code:
var parseDate = d3.time.format("%Y-%m-%d").parse;
//coerce data to dates
data.forEach(function (d) {
d.letter = parseDate(d.letter);
console.log(d.letter)
});
//set margins
var margin = {top: 40, right: 20, bottom: 60, left: 40},
width = 1000 - margin.left - margin.right,
height = 200 - margin.top - margin.bottom;
var formatPercent = d3.format(".0%");
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")
.tickFormat(d3.time.format("%Y-%m"));
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
var svg = div.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 + ")");
r2d3.onRender(function(data, s, w, h, options) {
x.domain(data.map(function(d) { return d.letter; }));
y.domain([0, d3.max(data, function(d) { return d.frequency; })]);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("transform", "rotate(270)")
.attr('dx', '-1.9em');
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("Frequency");
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter); })
.attr("width", x.rangeBand())
.attr("y", function(d) { return y(d.frequency); })
.attr("height", function(d) { return height - y(d.frequency); })
.on('mouseover', tip.show)
.on('mouseout', tip.hide)
});
function type(d) {
d.frequency = +d.frequency;
console.log(d);
return d;
}
Current Chart:
What I want:
Here's how D3 suggests filtering ordinal scales. This should only show your January ticks
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickValues(x.domain().filter(function(d, i) { return !(i % 12); }))

Multiple d3 charts on a page with different (linear and log) axes

I've built a page with five d3.js charts. Four of them use standard linear axes (linear data over time), and the fifth chart uses log/log axes. So far, I can get either the linear charts to render correctly, or the log/log chart to render correctly, but not both.
Question -- how can I define log/log axes for the final chart while keeping the first four linear charts working correctly?
<script src="//d3js.org/d3.v3.min.js"></script>
<script>
// Overall chart settings
var divwidth = $("#collapseOne").width();
var divheight = $(window).height();
var margin = {top: 25, right: 60, bottom: 35, left: 80},
width = divwidth - margin.left - margin.right,
height = 0.65*divheight - margin.top - margin.bottom;
var formatDate = d3.time.format("%Y-%m-%d");
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");
</script>
Then I define the first chart:
<script>
// Chart1 - NumofCompanies chart settings
var line1 = d3.svg.line()
.x(function(d) { return x(d.date); })
.y(function(d) { return y(d.cumcos); });
var chart1 = d3.select("#collapseOne")
.append("div")
.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.tsv("/monthly.tsv", 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.cumcos; }));
chart1.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart1.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("Number of companies");
chart1.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line1);
});
function type(d) {
d.date = formatDate.parse(d.date);
d.cumcos = +d.cumcos;
return d;
}
</script>
and then the log/log chart
<script>
// Chart5 - Log/log chart
var x = d3.scale.log()
.range([0, width]);
var y = d3.scale.log()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.orient("left");
var line5 = d3.svg.line()
.x(function(de) { return x(de.ordernum); })
.y(function(de) { return y(de.sumfunding); });
var chart5 = d3.select("#collapseFive").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.tsv("/loglog.tsv", type, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(de) { return de.ordernum; }));
y.domain(d3.extent(data, function(de) { return de.sumfunding; }));
chart5.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
chart5.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("Sum of Funding ($)");
chart5.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line5);
});
function type(de) {
de.ordernum = +de.ordernum;
de.sumfunding = +de.sumfunding;
return de;
}
</script>
edit - I've also tried renaming variables like this below and it still doesn't work; the axes are still linear. And when I try changing things like x.domain to xlog.domain and .x(function(de to .xlog(function(de then nothing on the chart renders at all.
<script>
// Chart5 - Log/log chart
var xlog = d3.scale.log()
.range([0, width]);
var ylog = d3.scale.log()
.range([height, 0]);
var xAxislog = d3.svg.axis()
.scale(xlog)
.orient("bottom");
var yAxislog = d3.svg.axis()
.scale(ylog)
.orient("left");
var line5 = d3.svg.line()
.x(function(de) { return x(de.ordernum); })
.y(function(de) { return y(de.sumfunding); });
var chart5 = d3.select("#collapseFive").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.tsv("/loglog.tsv", type, function(error, data) {
if (error) throw error;
x.domain(d3.extent(data, function(de) { return de.ordernum; }));
y.domain(d3.extent(data, function(de) { return de.sumfunding; }));
chart5.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxislog);
chart5.append("g")
.attr("class", "y axis")
.call(yAxislog)
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", 6)
.attr("dy", ".71em")
.style("text-anchor", "end")
.text("Sum of Funding ($)");
chart5.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line5);
});
function type(de) {
de.ordernum = +de.ordernum;
de.sumfunding = +de.sumfunding;
return de;
}
</script>
You are mistaking the first x in the line generator with the variable x in your scale:
var line5 = d3.svg.line()
.x(function(de) { return x(de.ordernum); })
//^--this has to be "x" ^--this is the scale
So, it has to be:
var line5 = d3.svg.line()
.x(function(de) { return xLog(de.ordernum); })
.y(function(de) { return yLog(de.sumfunding); });
According to the API of version 3:
line.x - get or set the x-coordinate accessor.
line.y - get or set the y-coordinate accessor.
As a good practice, avoid variable names like x. Instead, use names like xScale, xAxis, xPosition etc.

D3 Bar Chart Columns Overflowing

I am having an issue using d3 to create a bar chart where the column overflows the and the y axis labels are incorrect. Here is a fiddle http://jsfiddle.net/fajgvj9v/ that shows the issue. The data is parsing the <pre id="data"> tag to simulate a CSV I am using. If you change the value of 'a' to 5000 from 4000 it renders as expected.
<pre id="data">
name,count
a, 4000
b, 500
</pre>
yTitle = "Items";
var margin = {
top: 20,
right: 20,
bottom: 30,
left: 40
},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .1);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var y = d3.scale.linear()
.rangeRound([height, 0]);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.tickFormat(d3.format(".2s"));
var svg = d3.select("#malware_by_os").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 = d3.csv.parse( d3.select("pre#data").text() );
console.log(data);
var xLbl = d3.keys(data[0])[0];
var yLbl = d3.keys(data[0])[1];
data.sort(function(a, b) {
return b[yLbl] - a[yLbl];
});
x.domain(data.map(function(d) {
return d[xLbl];
}));
y.domain([0, d3.max(data, function(d) {
return d[yLbl];
})]);
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(yTitle);
svg.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) {
return x(d[xLbl]);
})
.attr("width", x.rangeBand())
.attr("y", function(d) {
return y(d[yLbl]);
})
.attr("height", function(d) {
return height - y(d[yLbl]);
});
The max function needs to convert to a number using +
y.domain([0, d3.max(data, function(d) {
return d[yLbl];
})]);
should be
y.domain([0, d3.max(data, function(d) {
return +d[yLbl];
})]);

D3 updating data but not axis

I am creating an interactive bar chart in D3. When a button is pressed the data changes.
Here's simplified code for the bar chart:
<svg class="cex"></svg>
<script>
var margin = {top: 20, right: 20, bottom: 60, left: 35},
width = 650 - margin.left - margin.right,
height = 300- margin.top - margin.bottom;
var x = d3.scale.ordinal()
.rangeRoundBands([0, width], .2);
var y = d3.scale.linear()
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");
var yAxis = d3.svg.axis()
.scale(y)
.outerTickSize(0)
.orient("left");
var cex = d3.select(".cex")
.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("/input.csv", function(error, data) {
x.domain(data.map(function(d) { return d.City; }));
y.domain([0, d3.max(data, function(d) { return d.EatIn; })]);
cex.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "rotate(60)")
.style("text-anchor", "start");;
cex.append("g")
.attr("class", "y axis")
.call(yAxis);
var bar=cex.selectAll(".bar")
.data(data)
.enter()
.append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.City); })
.attr("y", function(d) { return y(d.EatIn); })
.attr("height", function(d) { return height - y(d.EatIn); })
.attr("width", x.rangeBand());
});
function type(d) {
d.EatIn = +d.EatIn;
return d;
}
When a button is selected the following update code runs:
function EatOutData() {
d3.csv("/input.csv", function(error, data) {
x.domain(data.map(function(d) { return d.City; }));
y.domain([0, d3.max(data, function(d) { return d.EatOut; })]);
var sel = cex.selectAll("rect")
.data(data);
sel.exit().remove();
sel.enter().append("rect")
sel.attr("class", "bar")
sel.attr("x", function(d) { return x(d.City); })
sel.attr("y", function(d) { return y(d.EatOut); })
sel.attr("height", function(d) { return height - y(d.EatOut); })
sel.attr("width", x.rangeBand());
sel.selectAll("g.y.axis")
.call(yAxis);
sel.selectAll("g.x.axis")
.call(xAxis);
function type(d) {
d.EatOut = +d.EatOut;
return d;
}
}
)};
The update changes the Y variable. So the height of the bar changes but the axis doesn't change and the scale of the two variables are quite different.
There have been a couple other SO posts on this but none seemed to fix it for me. I'm not sure why the y.domain in the update doesn't adjust them. Would really appreciate any suggestions.
You will have to remove the axis (or the text) and draw it again just like you are removing the bars and plotting them again to update data on the axis. Check the working plnkr here.
function EatOutData() {
d3.csv("input2.csv", function(error, data) {
x.domain(data.map(function(d) { console.log(d); return d.City; }));
y.domain([0, d3.max(data, function(d) { return d.EatOut; })]);
var sel = cex.selectAll("rect")
.data(data);
sel.exit().remove();
d3.select(".x.axis").remove();
sel.enter().append("rect")
sel.attr("class", "bar")
sel.attr("x", function(d) { return x(d.City); })
sel.attr("y", function(d) { return y(d.EatOut); })
sel.attr("height", function(d) { return height - y(d.EatOut); })
sel.attr("width", x.rangeBand());
cex.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
.selectAll("text")
.attr("y", 0)
.attr("x", 9)
.attr("dy", ".35em")
.attr("transform", "rotate(60)")
.style("text-anchor", "start");;
sel.selectAll("g.y.axis")
.call(yAxis);
sel.selectAll("g.x.axis")
.call(xAxis);
function type(d) {
d.EatOut = +d.EatOut;
return d;
}
}
)};

Line chart in D3 is all over the place

everyone! Currently trying to generate a line chart using D3 with a simple JSON data. I'm using mbostock's line chart code, I just change data.tsv with my own JSON file:
[
{"date":"Aug-14","close":"1"},
{"date":"Feb-14","close":"2"},
{"date":"Jan-14","close":"1"},
{"date":"Jul-14","close":"3"},
{"date":"Jun-14","close":"1"},
{"date":"Mar-14","close":"3"},
{"date":"May-14","close":"1"},
{"date":"Nov-14","close":"1"},
{"date":"Oct-14","close":"1"},
{"date":"Sep-14","close":"1"}
]
However, I get a graph that looks like this crazy line chart
And I have no idea why it's drawing the lines like that. Any input would be amazing!
Edit: Adding the current code I'm using.
<script>
//Setting up...
var margin = {top: 20, right: 20, bottom: 30, left: 50},
width = 960 - margin.left - margin.right,
height = 500 - 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");
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.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 + ")");
d3.json("test.php", function(error, data) {
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
console.log(d.date);
});
x.domain(d3.extent(data, function(d) { return d.date; }));
y.domain(d3.extent(data, function(d) { return d.close; }));
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("Price ($)");
svg.append("path")
.datum(data)
.attr("class", "line")
.attr("d", line);
});
</script>
Hard to tell without looking directly at your code, but you might not be passing a Number into your scale function. In the source code you copied, see:
data.forEach(function(d) {
d.date = parseDate(d.date);
d.close = +d.close;
});
Or, just pass in data where close is a Number.
[
{"date":"Aug-14","close":1},
{"date":"Feb-14","close":2},
{"date":"Jan-14","close":1},
{"date":"Jul-14","close":3},
{"date":"Jun-14","close":1},
{"date":"Mar-14","close":3},
{"date":"May-14","close":1},
{"date":"Nov-14","close":1},
{"date":"Oct-14","close":1},
{"date":"Sep-14","close":1}
]
Edit:
Note also that the dates in the example you linked are sorted, yours are not.
var parseDate = d3.time.format("%b-%y").parse;
data.sort(function(a, b) {
return d3.ascending(parseDate(a.date), parseDate(b.date));
});

Categories