I'm having trouble working with json data in D3. The file is read properly, judging from the fact that it appears when I console.log, and seems to be formatted right based on the way all the examples I found. But, when I try to do a nested selection using .data(function(json_data){return json_data.accessibility;}) I get: "cannot read property 'length' of undefined".
My function:
//load scenario json data
d3.json("./SupportTool/scenario1result.json", function(error, json_data){
if(error) {return console.warn(error)};
console.log(json_data); //works
// add main SVG block
var svg = d3.select(d3id)
.append('svg')
.attr('width', 300)
.attr('height', 75)
.attr('id', 'svgblock');
// add an SVG group element for each scenario
var series = svg.selectAll('g.series')
.data(d3.keys(json_data))
.enter()
.append('g')
.attr('class', 'series');
var circles = series.selectAll("circle")
.data(function(json_data){return json_data.accessibility;})
.enter()
.append("circle");
var circleAttributes = circles
.attr("cx", 20)
.attr("cy", 20)
.attr("r", 20)
.style("color","blue"); });
My json data:
{
"meta":[{"sc":"1"},{"stratid":"1"}],
"accessibility":[
{"pop400":"77"},{"pop800":"86"},{"jobs800":"78"},{"pop400tr":"41"},{"pop800tr":"69"},{"jobs800tr":"80"}
],
"housing":[
{"newcom":"0"},{"redev":"100"},
{"apt5":"6"},{"apt4":"65"},{"twn":"14"},{"sglf":"15"},
{"urb":"0"},{"urbhec":"0"}
],
"transport":[
{"walk":"55"},{"transit":"18"},{"auto":"27"},
{"vkt":"11000"},
{"kmtr":"502"},{"form":"grid"},
{"lanekm":"3250"},
{"ghgtr":"67"},{"ghgres":"75"}
],
"costs":[
{"roadcapbils":null,"roadcap":null},
{"transitcapbils":null,"transitcap":null},
{"watercapbils":null,"watercap":null},
{"firecapbils":null,"firecap":null},
{"reccapbils":null,"reccap":null},
{"educapbils":null,"educap":null}
],
"opcosts":[
{"roadopbils":null,"roadop":null},
{"transitoppbils":null,"transitop":null},
{"wateropbils":null,"waterop":null},
{"fireopbils":null,"fireop":null},
{"parksopbils":null,"parksop":null}
] }
The issue you are having comes from the fact that you are binding data to circles using a function of the data already bound to series:
var circles = series.selectAll("circle")
series already has data bound to it from .data(d3.keys(json_data)). Thus, when you log the objects being passed one at a time to the .data() for circles, you just get the keys of json_data, i.e.
["meta", "accessibility", "housing", "transport", "costs", "opcosts"]
Since this is a list of Strings, they do not have any property called accessibility, hence your error.
My guess is that you are trying to append circles for each item in json_data.accessibility, which your code will do if you just replace that line with
.data(json_data.accessibility)
which will pass
[{"pop400":"77"},{"pop800":"86"},{"jobs800":"78"},{"pop400tr":"41"},{"pop800tr":"69"},{"jobs800tr":"80"}]
to data. This code works on my machine, and draws six circles on the page.
One final note is that you should be careful with your variable names. In the function you pass to data, you are redefining json_data as a local variable in that function, which means you can't access your actual JSON data in that function.
Related
I'm working on creating a graph that will show unemployment rates by county in the United States. It's based on Mike Bostock's County-level map here, and it looks like this:
It works by pulling data from a CSV, assigning that data to a Javascript Map, and using that to color the various counties with a d3 color scale. My CSV data looks like this:
county,area,rate2007,rate2008,rate2009,rate2010,rate2011,rate2012,rate2013,rate2014,rate2015,rate2016
01001,Autauga County,3.3,5.1,9.7,8.9,8.4,6.9,6.2,5.9,5.3,5.3
01003,Baldwin County,3.1,4.6,9.8,10.0,9.0,7.5,6.6,6.1,5.6,5.4
01005,Barbour County,6.3,8.8,14.3,12.3,11.5,11.5,10.2,10.6,8.8,8.6
01007,Bibb County,4.1,5.8,13.3,11.4,10.5,8.5,7.9,7.2,6.7,6.6
01009,Blount County,3.2,4.7,10.0,9.8,8.7,6.9,6.3,6.1,5.4,5.5
etc...
Here's my issue: I want to be able to change this data over time, and to do so must be able to include multiple values in my Map. However, I cannot get this to work. In attempting to "upgrade" my map, I tweak the code slightly to use an array as the value in the key-value pair in the Map:
d3.queue()
.defer(d3.json, "https://d3js.org/us-10m.v1.json")
.defer(d3.csv, "unemploymentEdited.csv", function(d) {
unemployment.set(d.county, [+d.rate2007, +d.rate2008]);
}) // I use an array here to include multiple values.
.await(ready);
When I log this to the console, my data is indeed formatted as I would expect:
However, I cannot use these values to color my paths correctly. When I use a relatively simple function to access the data from the Map, it logs this error to the console: "TypeError: unemployment.get(...) is undefined."
Even more strangely, when I log this same thing to the console outside of my "fill" attribute, I get the number I would expect, meaning I get the values inside my Map. Like if I write console.log(unemployment.get(d.id)[0]) I get 4.6, or whatever the value is. What am I doing wrong? Why does the "get" function return undefined, even though I can see that the data structure is not?
Here's my full code:
var width = 960;
var height = 600;
var margin = {top: 50, bottom: 0, left: 0, right: 0}
var path = d3.geoPath(); // Geopath generator
var unemployment = new Map();
var color = d3.scaleSequential()
.domain([0.0,30.0])
.interpolator(d3.interpolateInferno);
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.bottom + margin.top)
.style("background-color","lightgrey")
d3.queue()
.defer(d3.json, "https://d3js.org/us-10m.v1.json")
.defer(d3.csv, "unemploymentEdited.csv", function(d){
unemployment.set(d.county, [+d.rate2007,+d.rate2008])
})
.await(ready);
function ready(error, us) {
console.log(unemployment)
svg.append("g")
.attr("class", "counties")
.attr("transform",`translate(0,${margin.top})`)
.selectAll("path")
.data(topojson.feature(us, us.objects.counties).features)
.enter().append("path")
.attr("fill", function(d){
return color(unemployment.get(d.id)[0])
})
.attr("d", path)
}
Well, your d3.map() is correct, that's not the problem.
The problem is that your CSV doesn't have data for all counties. Therefore, sometimes, this...
unemployment.get(d.id)
... is undefined, which explains your error:
unemployment.get(d.id)[0] --> Cannot read property '0' of undefined
Solution
Check for undefined:
.attr("fill", function(d){
return unemployment.get(d.id) ? color(unemployment.get(d.id)[0]) : "#ccc";
})
Here, if unemployment.get(d.id) is undefined, the function will return #ccc. Change this according to the colour you want.
Here is the updated bl.ocks: https://bl.ocks.org/anonymous/3adc7518e4423d816f6b6842ef48d27f/414e4b738dd4c2d8e91a9ca2fb8511dcec747b9c
I am trying to upgrade this stackable bar chart to v4.
Everything works except for one thing.
When I filter one category the bars don't drop to the start of the x-axis. I get an error which says:
state.selectAll(...).forEach is not a function
I've tried multiple things but I can't figure this one out.
This is the broken code:
function plotSingle(d) {
class_keep = d.id.split("id").pop();
idx = legendClassArray.indexOf(class_keep);
//erase all but selected bars by setting opacity to 0
d3.selectAll(".bars:not(.class" + class_keep + ")")
.transition()
.duration(1000)
.attr("width", 0) // use because svg has no zindex to hide bars so can't select visible bar underneath
.style("opacity", 0);
//lower the bars to start on x-axis
state.selectAll("rect").forEach(function(d, i) {
//get height and y posn of base bar and selected bar
h_keep = d3.select(d[idx]).attr("height");
y_keep = d3.select(d[idx]).attr("y");
h_base = d3.select(d[0]).attr("height");
y_base = d3.select(d[0]).attr("y");
h_shift = h_keep - h_base;
y_new = y_base - h_shift;
//reposition selected bars
d3.select(d[idx])
.transition()
.ease("bounce")
.duration(1000)
.delay(750)
.attr("y", y_new);
})
}
I find it strange that this works flawlessly in D3 v3, why wouldn't this work in v4?
In d3 v3 selectAll returned an array, in d3 v4 it returns an object.
From the v3 notes:
Selections are arrays of elements—literally (maybe not literally...).
D3 binds additional methods to the array so that you can apply
operators to the selected elements, such as setting an attribute on
all the selected elements.
Where as changes in v4 include:
Selections no longer subclass Array using prototype chain injection;
they are now plain objects, improving performance. The internal fields
(selection._groups, selection._parents) are private; please use the
documented public API to manipulate selections. The new
selection.nodes method generates an array of all nodes in a selection.
If you want to access each node in v4 try:
selection.nodes().forEach( function(d,i) { ... })
But, this is just the node, to get the data you would need to select each node:
var data = [0,1,2];
var svg = d3.select("body").append("svg")
.attr("width",500)
.attr("height",200)
var circles = svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d,i) { return i * 20 + 50 })
.attr("cy", 50)
.attr("r", 4);
circles.nodes().forEach(function(d,i) {
console.log(d3.select(d).data());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
But, if you need the data or to modify the selection properties, it could be easier to use selection.each(). d3.each iterates through each element of a d3 selection itself, and allows you to invoke a function for each element in a selection (see API docs here):
var data = [0,1,2];
var svg = d3.select("body").append("svg")
.attr("width",500)
.attr("height",200)
var circles = svg.selectAll("circle")
.data(data)
.enter()
.append("circle")
.attr("cx", function(d,i) { return i * 20 + 50 })
.attr("cy", 50)
.attr("r", 4);
circles.each( function() {
console.log(d3.select(this).data());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
In v3 of this bar chart, in the forEach loop
`states.selectAll("rect").forEach(function(d,i) {`
d is an array of nodes (the rectangles in each .g).
But, in v4 d3 selections aren't arrays, you can't use a forEach loop in the same way. But you can still get the nodes in it without much modification using selection.nodes() and than get the childNodes to replicate the array in the v3 version:
state.nodes().forEach(function(d, i) {
var nodes = d.childNodes;
Here we go through each element/node in state and get the child rects, returned as an array. Here's an updated fiddle.
I am currently creating a barchart that gets data from a d3 histogram.
I create the histogram like this:
var binningThresholds = d3.range(getMinValue(rows, 'Model year'), getMaxValue(rows, 'Model year') + 2)
var histogram = d3.layout.histogram()
.value(getModelYear)
.bins(binningThresholds)
(rows);
I get rows from a csv input. I do a lot of stuff with the input already, so that works fine.
The histogram now is an array of an array of objects.
When I now want to use this histogram and add a bar to a chart for every index in the array, no error shows up and d3 does not append any g, rect or text tags to the DOM.
var histogramBars = histogramSvg.selectAll('g')
.data(histogram)
.enter()
.append('g');
histogramBars.append('rect');
histogramBars.append('text')
.text(function(d) {
return d.length;
})
I really don't know why, does anyone see a mistake?
Don't use .selectAll('g').data..., my guess is that there's other g elements in your visualization and you are selecting things you don't mean to. Instead do something like:
var histogramBars = histogramSvg.selectAll('.myUniqueClass')
.data(histogram)
.enter()
.append('g')
.attr('class', 'myUniqueClass');
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.
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.