How do I update my multiple line chart data in D3? - javascript

I've picked apart a couple of different examples to get as far as I have. I have a simple two-line line chart being fed by an object. For testing, I created a function that increments the data by adding a new datapoint to the end. I would like my chart to reflect those additions.
What works:
The data gets added to the object.
When button clicked, YScale adjusts
What doesn't work:
XScale doesn't adjust for new data.
Team 1 line adapts Team2 line's data and then scales along the Y accordingly.
It's a mess. And Just when I think I understand D3, the data incorporation humbles me!
Here's some code and a mostly-working fiddle.
UPDATED: Here's an updated fiddle that has it working as expected. I know D3 makes a lot of this stuff easier so, while it works, I'm looking for a more graceful way to get the same outcome.
My data format...
//SET SAMPLE DATA
var data = [{
"team": "Team 1",
"score": 0,
"elapsedTime": 0
}, {
"team": "Team 1",
"score": 2,
"elapsedTime": 3
},
...
{
"team": "Team 2",
"score": 18,
"elapsedTime": 60
}];
My update function...
function updateChart(){
//SPLIT UPDATED DATA OBJECT INTO TWO TEAMS
dataGroup = d3.nest()
.key(function(d) {
return d.team;
})
.entries(data);
//DRAW LINES
dataGroup.forEach(function(d, i) {
// Select the section we want to apply our changes to
var vis = d3.select("#visualisation").transition();
xScale.domain([0, d3.max(data, function(d) {
return d.elapsedTime;
})]);
yScale.domain([0, d3.max(data, function(d) {
return d.score;
})]);
//PROBLEM: Team 1 line changes to Team 2's data
vis.select("#line_team1")
.duration(750)
.attr("d", lineGen(d.values));
});
vis.select("#line_team2")
.duration(750)
.attr("d", lineGen(data));
// X-SCALE NEVER ADJUSTS
vis.select(".x.axis") // change the x axis
.duration(750)
.call(xAxis);
// Y-AXIS SEEMS TO SCALE AS EXPECTED
vis.select(".y.axis") // change the x axis
.duration(750)
.call(yAxis);
};
Any insight would be greatly appreciated!

One way to further simplify your code is to change it to update based on the data itself.
A method that I often use is obtaining the selector for updating the data from the data itself. In your case you could use the key property of your dataGroup objects:
dataGroup.forEach(function(d, i) {
vis.select("#line_"+d.key.toLowerCase().split(' ').join(''))
.duration(750)
.attr("d", lineGen(d.values));
var maxi = d3.max(data, function(d) {
return d.elapsedTime;
});
...
});
Or you could do the preprocessing in your d3.nest() call in order to obtain the key in form of team1 and use it as a selector.
Here's a fork of your fiddle with working example.

Related

How to use d3 filter and update function to toggle between data selections

I'm trying to get to grips with d3 by creating a bar chart of house prices based on whether the property address ends with 'Street', 'Road', 'Way' etc.
However, I'd also like the view of the data to change based on a column of data for local neighbourhoods.
It's the second query on this topic. Here's the previous query - How to extract nominal labels for d3 chart
You can see the structure of the data extracted through Pandas' to_json function here: http://plnkr.co/edit/He3yPUfuE8k7hvIkupjS?p=preview
I've used a nest function to key the data on the the local areas, but can't work out how to plug in a d3.filter method to restrict the data to a selected area.
I've got a function which creates a select button based on the keys:
var options = dropDown.selectAll("option")
.data(nested_data)
.enter()
.append("option");
options.text(function (d) { return d.key; })
.attr("value", function (d) { return d.key; });
But what I can't work out is how to plug the value from this selection into the plotting part of the d3 script.
d3.select("svg")
.selectAll("circle")
.data(nested_data)
.enter()
.append("circle")
d3.selectAll("circle")
.attr("cx", function(d) {
console.log(d["street_name"]);
return street_scale(d["street_name"]);
})
.attr("cy", function(d) {
return price_scale(d["value"]);
})
.attr("r", 5)
.attr("fill", "steelblue");
And while I know I need an update function to continue to change the chart as users select between, I've not found an example that I can adapt.
Thank you in advance for your patience - I'm very new to d3 and a Javascript noob.
Think about the data structure you want in the end. Since d3 likes arrays of objects and you want to filter by district, I'm picturing this:
var data = {
district1: [
{
street_split: 'a',
value: 1
},{
street_split: 'b',
value: 2
}
],
district2: [
{
street_split: 'a',
value: 1
},{
street_split: 'b',
value: 2
}
],
etc...
Your filter then simply becomes:
data[someDistrict]
So, how do we get your data in this format. I'd do everything in one loop, the data, the extents, the labels, etc...:
var orgData = {}, // our final data like above
street_labels = d3.set(), // set of streets
districts = d3.set(), // set of districts
minVal = 1e99, // min of values
maxVal = -1e99; //max of values
data.forEach(function(d){
d.value = +d.value; // convert to numeric
street_labels.add(d.street_split); // set of street_labels
districts.add(d.district); // set of districts
if (d.value < minVal) minVal = d.value; // new min?
if (d.value > maxVal) maxVal = d.value; //new max?
if (!orgData[d.district]){ // we want a associate array with keys of districts
orgData[d.district] = []; // and values that are arrays of object
}
orgData[d.district].push({ // those objects are street_split and value
street_split: d.street_split,
value: d.value
});
});
Now how do we update on a different select? That simply becomes:
dropDown.on("change", function() {
d3.selectAll("circle")
.data(orgData[this.value]) // new data
.attr("cx", function(d) { // update attributes
return street_scale(d.street_split);
})
.attr("cy", function(d) {
return price_scale(d.value);
});
});
Here's my working code.

D3: Passing object array data to a barchart on mouseover

Working with two charts in D3. I have a pie chat displaying parent data regarding a budget. When the user mouses over a pie slice, I am trying to push that slice's array data to a bar chart.
My data is setup like so:
{"Department":"Judiciary",
"Funds1415":317432,
"Fundsb":"317.4",
"annual": [ 282,288,307,276,276,298,309,317,317 ]
},
I'm trying to use this to pass the annual array to the barchart:
path.on('mouseover', function(d) {
...
bars.selectAll('rect').transition().attr("y", function(d) { return h - d.data.annual /125; });
bars.selectAll('rect').transition().attr("height", function(d) { return d.data.annual / 125; });
});
And here's the barchart I'm trying to send it to:
var bars = svg.selectAll("rect")
.data(budget)
.enter()
.append("rect")
.attr("class", "barchart")
.attr("transform", "translate(26,109)")
.attr("fill", function(d, i) {
return color2(i);
})
.attr('class', 'barchart')
.attr("x", function(d, i) {
return i * 14;
})
.attr("width", 12)
.attr("y", 100)
.attr("height", 100);
Link to full code here:
http://jsbin.com/zayopecuto/1/edit?html,js,output
Everything 'seems' to be working, except the data either isn't passing or it isn't updating the bar chart.
I've been banging my head up against this for a couple of days, to no avail. Originally I was thinking of placing the annual data in separate arrays and just transitioning from data source to data source on mouseover, but that seems backward and unnecessary.
First, your selector is wrong. bars is already a collection of rects, so you can't re-select the rects. Second, you haven't bound "updated" data to those rects. So, with this in mind, it becomes:
bars
.data(d.data.annual)
.transition()
.attr("height", function(d) {
return d / 125;
})
.attr("y", function(d) {
return h - d /125;
});
Here's an updated example.
What I understand from your code and comment is that, you have data points for your donut chart and each data object contains a property called 'annual' which you want to use as a input data for the bar chart.
You should be calling a separate function to plot your bar chart passing it the annual data array.
Clear the existing bar chart on 'mouseout' event, so that a new bar chart can be plotted on the next 'mouseover' event. You can use jQuery empty() function for clearing out the chart container.

multiple circles / lines using d3.js

I have a d3.js problem and have struggled with this for a while and just can not seem to solve it. I believe it is pretty easy, but am missing something very basic.
Specifically, I have the following code, which generates a line and 2 circles for the 1st entry in the JSON - I have 'hardcoded' it for the first entry.
I'd like to now add the 2nd and 3rd entries of the JSON file to the graph and have control over line and circle colors and then generalize the code.
From reading the documentation and StackOverflow, it seems like the proper approach is to use nesting, but I can't seem to make it work?
The code is on jsfiddle at the following URL and the javascript is below.
http://jsfiddle.net/GVmVk/
// INPUT
dataset2 =
[
{
movie : "test",
results :
[
{ week: "20130101", revenue: "60"},
{ week: "20130201", revenue: "80"}
]
},
{
movie : "beta",
results :
[
{ week: "20130101", revenue: "40"},
{ week: "20130201", revenue: "50"}
]
},
{
movie : "gamm",
results :
[
{ week: "20130101", revenue: "10"},
{ week: "20130201", revenue: "20"}
]
}
];
console.log("1");
var parseDate = d3.time.format("%Y%m%d").parse;
var lineFunction = d3.svg.line()
.x(function(d) { return xScale(parseDate(String(d.week))); })
.y(function(d) { return yScale(d.revenue); })
.interpolate("linear");
console.log("2");
//SVG Width and height
var w = 750;
var h = 250;
//X SCALE AND AXIS STUFF
//var xMin = 0;
//var xMax = 1000;
var xScale = d3.time.scale()
.domain([parseDate("20130101"),parseDate("20131231")])
.range([0, w]);
console.log(parseDate("20130101"));
console.log("3");
var xAxis = d3.svg.axis()
.scale(xScale)
.orient("bottom");
console.log("4S");
//Y SCALE AND AXIS STUFF
var yScale = d3.scale.linear()
.domain([0, 100])
.range([h, 0]);
var yAxis = d3.svg.axis()
.scale(yScale)
.orient("left")
.ticks(5);
//Create SVG element
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
console.log("4S1");
//CREATE X-AXIS
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(0," + (h - 30) + ")")
.call(xAxis);
//Create Y axis
svg.append("g")
.attr("class", "axis")
.attr("transform", "translate(" + 25 + ",0)")
.call(yAxis);
svg.selectAll("circle")
.data(dataset2[0].results)
.enter()
.append("circle")
.attr("cx", function(d) {
// console.log(d[0]);
console.log(parseDate(d.week));
return xScale(parseDate(d.week));
})
.attr("cy", function (d) {
return yScale(d.revenue);
})
.attr("r", 3);
//create line
var lineGraph = svg.append("path")
.attr("d", lineFunction(dataset2[0].results))
.attr("class", "line");
The word "nesting" comes up in two contexts in d3 -- creating nested data arrays with d3.nest, and using nested data to create nested selections.
Your data is already in the correct format for a nested selection -- an array of objects, each of which has a sub-array of individual data points. So you don't need to worry about manipulating the data, you just need to go straight to joining your data to your elements in nested d3 selections:
I'm going to take you through it quickly, but the following tutorials will be good reference for the future:
Thinking with Joins
Nested Selections
How Selections Work
On to your example: you have a top-level data structure that is an array of movie objects, each of which contains a sub-array of weekly revenue values. The first thing you need to decide is what type of elements you want associated with each level of data. You're drawing a line and a set of circles for the data in the sub-array, but aren't currently adding anything for the top-level array objects (the movies). You need to add something for them in order for nested selections to work, and it needs to be something that can contain your line and circle. In SVG, that's almost always going to be a <g> (grouping) element.
To efficiently create one <g> element for every object in your data array -- and to attach the data objects to the elements for future reference -- you create an empty selection, join your data to it, then use the enter() method of the data join selection to add elements for each data object that didn't match an element. In this case, since we don't have any elements to start, all the data objects will be in the enter() selection. However, the same pattern also works when updating some of the data.
var movies = svg //start with your svg selection,
//it will become the parent to the entering <g> elements
.selectAll("g.movie") //select all <g> elements with class "movie"
//that are children of the <svg> element
//contained in the `svg` selection
//this selection will currently be empty
.data( dataset2 ); //join the selection to a data array
//each object in the array will be associated with
//an element in the selection, if those elements exist
//This data-joined selection is now saved as `movies`
movies.enter() //create a selection for the data objects that didn't match elements
.append("g") //add a new <g> element for each data object
.attr("class", "movie") //set it's class to match our selection criteria
//for each movie group, we're going to add *one* line (<path> element),
//and then a create subselection for the circles
.append("path") //add a <path> within *each* new movie <g> element
//the path will *inherit* the data from the <g> element
.attr("class", "line"); //set the class for your CSS
var lineGraph = movies.select("path.line")
//All the entered elements are now available within the movies selection
//(along with any existing elements that we were updating).
//Using select("path") selects the first (and only) path within the group
//regardless of whether we just created it or are updating it.
.attr("d", function(d){ return lineFunction(d.results); });
//the "d" attribute of a path describes its shape;
//the lineFunction creates a "d" definition based on a data array.
//If the data object attached to the path had *only* been the d.results array
//we could have just done .attr("d", lineFunction), since d3
//automatically passes the data object to any function given as the value
//of an .attr(name, value) command. Instead, we needed to create an
//anonymous function to accept the data object and extract the sub-array.
var circles = movies.selectAll("circle")
//there will be multiple circles for each movie group, so we need a
//sub-selection, created with `.selectAll`.
//again, this selection will initially be empty.
.data( function(d) {return d.results; });
//for the circles, we define the data as a function
//The function will be called once for each *movie* element,
//and passed the movie element's data object.
//The resulting array will be assigned to circles within that particular
//movie element (or to an `enter()` selection, if the circles don't exist).
circles.enter() //get the data objects that don't have matching <circle> elements
.append("circle") //create a circle for each
//the circles will be added to the appropriate "g.movie"
//because of the nested selection structure
.attr("r", 3); //the radius doesn't depend on the data,
//so you can set it here, when the circle is created,
//the same as you would set a class.
circles //for attributes that depend on the data, they are set on the entire
//selection (including updating elements), after having created the
//newly entered circles.
.attr("cx", function(d) { return xScale( parseDate(d.week) ); })
.attr("cy", function(d) { return yScale( d.revenue ); });
Live version with the rest of your code: http://jsfiddle.net/GVmVk/3/
You'll need to adjust the domain of your x-scale so that the first data points aren't cut off, and you'll need to decide how you want to use your movie title property, but that should get you going.
Yes indeed, nested selection are the way to go for the circles, although you don't need them for the paths:
svg.selectAll("g.circle")
.data(dataset2)
.enter()
.append("g")
.attr("class", "circle")
.selectAll("circle")
.data(function(d) { return d.results; })
.enter()
.append("circle")
.attr("cx", function(d) {
// console.log(d[0]);
console.log(parseDate(d.week));
return xScale(parseDate(d.week));
})
.attr("cy", function (d) {
return yScale(d.revenue);
})
.attr("r", 3);
//create line
var lineGraph = svg.selectAll("path.line")
.data(dataset2).enter().append("path")
.attr("d", function(d) { return lineFunction(d.results); })
.attr("class", "line");
Complete example here.

Legend to D3.js scatterplot

I have created a scatter chart with multiple y-axis.
I need to create a legend to indicate the scattering.
I have created a fiddle of the same in the link provided in comments.
Please help me out.
The reason is that in your code colors is an object, not an array.
D3 expects the data that is passed to it to be an array:
I've updated your fiddle - see http://jsfiddle.net/y3LEt/3/
The critical updates are:
var colors = [["Local", "#377EB8"],
["Global", "#4DAF4A"]];
legendRect
.attr("y", function(d, i) {
return i * 20;
})
.style("fill", function(d) {
return d[1];
});

Bar chart with d3.js and an associative array

I give up, I can't figure it out.
I was trying to create a bar chart with 3d.js but I can't get it working. Probably I don't understand it enough to deal with my complicate associative array.
My array has the following structure:
{"January"=>{"fail"=>13, "success"=>6},
"February"=>{"success"=>10, "fail"=>4},
"March"=>{"success"=>9, "fail"=>13},
"April"=>{"success"=>16, "fail"=>5},
"May"=>{"fail"=>52, "success"=>23},
"June"=>{"fail"=>7, "success"=>2},
"July"=>{},
"August"=>{"fail"=>6, "success"=>3},
"September"=>{"success"=>54, "fail"=>59},
"October"=>{"success"=>48, "fail"=>78},
"November"=>{"fail"=>4, "success"=>6},
"December"=>{"fail"=>1, "success"=>0}}`
I got the displaying of the axis working:
The code looks really ugly because I converted the names to a "normal" array:
monthsNames = new Array();
i = 0;
for (key in data) {
monthsNames[i] = key;
i++;
}
x.domain(monthsNames);
y.domain([0, 100]);
But I can't figure it out how to deal with the data.
I tried things like, svg.selectAll(".bar").data(d3.entries(data))
What is a good beginning I guess but I can't get the connection to the axis working.
What I want to create is a bar-chart that has the months as x-axis and every month has two bars (respectively one bar with two colours) - one for success and one for fail.
Can anybody please help me how to handle the data? Thanks in advance!
EDIT:
I cannot figure out how to scale x and y. If I use this code:
var x = d3.scale.ordinal()
.domain(monthsNames)
.range([0, width]);
var y = d3.scale.linear()
.domain([0,100])
.range([0, height]);
nothing is shown up then. If I print out the values that evaluate after using e.g. x(d.key) or x(d.value.fail) they are really strange numbers, sometimes even NaN.
EDIT:
d3.selectAll(".barsuccess")
.on('mouseover', function(d){
svg.append('text')
.attr("x", x(d.key))
.attr("y", y(d.value.success))
.text(d.value.success+"%")
.attr('class','success')
.style("font-size","0.7em")
})
.on('mouseout', function(d){
d3.selectAll(".success").remove()
});
d3.selectAll(".barfail")
.on('mouseover', function(d){
svg.append('text')
.attr("x", x(d.key)+x.rangeBand()/2)
.attr("y", y(d.value.fail))
.text(d.value.fail+"%")
.attr('class','fail')
.style("font-size","0.7em")
})
.on('mouseout', function(d){
d3.selectAll(".fail").remove()
});
Be sure to check out the bar chart tutorials here and here. You have basically all you need already. The connection between the axes and the data are the functions that map input values (e.g. "March") to output coordinates (e.g. 125). You (presumably) created these functions using d3.scale.*. Now all you need to do is use the same functions to map your data to coordinates in the SVG.
The basic structure of the code you need to add looks like
svg.selectAll(".barfail").data(d3.entries(data))
.enter().append("rect")
.attr("class", "barfail")
.attr("x", function(d) { x(d.key) })
.attr("width", 10)
.attr("y", function(d) { y(d.value.fail) })
.attr("height", function(d) { y(d.value.fail) });
and similar for success. If you use the same scale for the x axis for both types of bar, add a constant offset to one of them so the bars don't overlap. Colours etc can be set in the CSS classes.

Categories

Resources