D3JS Map Citiy Circles - json

I'm currently creating a map of germany with d3js to visualize some data. I now added some Cities by using a csv, which are shown as circles in the map. I want some cities to have a different color the more data are used in them. Does anybody have a idea how I can achieve this?

You can declare a range of color like this:
var color = d3.scale.linear()
.domain([d3.min(array), d3.max(array)])
.range(["#fff7f3", "#49006a"]);
then style every circle:
.style("fill", function(d) {
return color(+d.data);
});
But you need to compact your data to just one value per city like so:
d.values.reduce(function(sum, d){
return sum + d.amount;
},0)
Here's an example from Mike's Site: http://bl.ocks.org/mbostock/4060606

Related

Use only the 5 higher values in amCharts pie?

My data call can have lots of small elements (in percentage) that I would like to ignore, I only need the top 5 in my amCharts pie.
Can this be accomplished with amCharts or I should treat the data before?
please see my [jsfiddle][1]
[1]: http://jsfiddle.net/pbarros/xznxbnc7/3/
thanks
You can use the hideLabelsPercent property to set a threshold for the lowest allowed percentage you want a label for. If you want to do this dynamically, you can set this in the init event by finding the 5th largest percents value in the chart's chartData array and use it as your hideLabelsPercent threshold. I've updated your handleInit method to do this:
function handleInit(e) {
if (e.chart.chartData.length > 5) {
//sort the copy of the chartData array from largest to smallest
//if your data is pre-sorted, then you can skip this step
var sortedData = e.chart.chartData.slice().sort(function(lhs, rhs) {
return rhs.percents - lhs.percents;
});
//set the threshold equal to the 5th largest slice's percents value so that the rest are hidden
e.chart.hideLabelsPercent = sortedData[4].percents;
//redraw the chart
e.chart.validateNow();
}
}
Updated fiddle: http://jsfiddle.net/xznxbnc7/9/
Edit since I misread the question
If you only want to show the top five slices from your dataset, you can filter on your backend or use the init method to sort and modify your dataProvider to contain only the top five.
function handleInit(e) {
if (e.chart.chartData.length > 5) {
//sort the copy of the chartData array from largest to smallest
//if your data is pre-sorted, then you can skip this step
var sortedData = e.chart.dataProvider.slice().sort(function(lhs, rhs) {
return rhs[e.chart.valueField] - lhs[e.chart.valueField];
});
//only put in the top 5.
e.chart.dataProvider = sortedData.slice(0, 5);
// redraw the chart
e.chart.validateData();
}
}
Fiddle: http://jsfiddle.net/g3cchyjg/1

how to filter a JSON file? (NYC Census Tracts)

I am adapting an existing D3JS map-drawing file to work with a different JSON file. In the file 'ny.json' there are things called "objects" and inside of those there are things called "tracts" so I get how the references work for the current (working) code, which comes from here and looks like:
d3.json("./shapefiles/ny.json", function(error, ny) {
if (error) throw error;
var tracts = ny.objects.tracts;
tracts.geometries = tracts.geometries
.filter(function(d) { return (d.id / 10000 | 0) !== 99; });
svg.append("g")
.selectAll("path")
.data(topojson.feature(ny, tracts).features)
.enter().append("path")
.attr("class", "tract")
.attr("d", path)
However, the new JSON file doesn't have those 'objects' or 'tracts' and I'm trying to figure out how to filter it so that it can be used to draw a map not of New York State (as in the first one) but just of the Bronx county. It's possible that the two files are too different in structure that an easy filter change isn't possible, but I thought I would ask in case there's another solution. I haven't seen the 'meta' features in json before.
I am afraid it is not possible to display only Bronx in the map because census tract ids in ny.json are unique only at borough level. For instance, census tract 014300 appears in Bronx, Brooklyn, Manhattan, and Queens. ny.json stores only census tract ids in ny.objects.tracts.id, and not their FIPS County Codes.
This makes filtering on Borough name impossible: https://bl.ocks.org/memoryfull/ba6121d19f80f85f0beb
Even if the filtering was feasible, it would be suboptimal. Instead, I would create own GeoJSON of Bronx in any GIS software with census tract ids and then call it in your d3 code.

Two tooltip points on one path in d3.js line chart

I've made this simple line chart in d3, but as well as showing the tooltip data for mouseover, I would also like to display the data for where the blue dotted line of the tooltip intersects with the data path in the first instance.
For intsance at the link below, if the mouse hovers at 2012, data for 2005 would show at the first intersection between the tooltip line and the data path.
http://bl.ocks.org/anonymous/49f04076adbec7e2c2f9
Any ideas? Thanks
In the linked example, you would want to search for months with CPI intervals that contain the CPI value that is currently displayed. So, create a list of such intervals, with references to the month that contains them, then find matching intervals on hover.
Something like this, for example (untested):
// after loading data
var cpi_intervals = [];
data.forEach(function(d, i) {
if (i > 0) {
cpi_intervals.push({
cpis: d3.extent([data[i-1].cpi, d.cpi]),
date: d.date
});
}
});
...
// function to find months containing specified cpi
function monthsContainingCPI(cpi) {
return cpi_intervals.filter(function(d) {
return cpi >= d.cpis[0] && cpi < d.cpis[1];
}).map(function(d) {return d.date;})
}
If needed, you can improve the performance of the monthsContainingCPI function by using a more complex data structure, like an interval tree, to store and access the CPI intervals.

D3 reusable multi-line chart with JSON data

I'm trying to do some re-factoring on my charts to make them re-usable using this as a guide: http://bost.ocks.org/mike/chart/
I'm having problems drawing the lines in my multi-line graph though - specifically passing the data to the x and y values. If I hard code the element names it works, but if I try to use the xValue and yValue objects this does not work. I'm assuming that this is because I'm trying to call a function within the parameter of an other object, but I'm not sure how to get around this. In the exmaple Mike uses d[0] and d[1], but this won't work with JSON data (or I'm not sure how to make it work).
I've posted this JSFiddle so you can see the code. The problem lines are 125 to 131 which in turn is being called from line 165.
var main_line = d3.svg.line()
.interpolate("cardinal")
// Hard coding the elements works
//.x(function(d) { return main_x(d.date); })
//.y(function(d) { return main_y(d.buildFixTime); });
// Passing xValue and yValue does not work
.x(function(d) { return main_x(xValue); })
.y(function(d) { return main_y(yValue); });
http://jsfiddle.net/goodspeedj/fDyLY/
Thank you in advance.
You need to redefine your accessor method within .x() and .y(). The accessor method defines the way that a datum is pulled out of the data that is bound to the selection that you call the line generator on.
Suppose you have a relatively flat data structure such as the following.
data = [{x : 1, y : 2}, {x:1, y:3}, {x:4, y:5}];
You then bind the data to a selection with the following statement
d3.select("body").datum(data).append("path").attr("d",lineGenerator);
Quite a bit is going on underneath this statement. I'll give you a bit more of a walkthrough after showing you a commonly used example.
The important aspect to understand is that similarly to other calls in d3 such as
var exampleRectangles = d3.select("body")
.data(data).enter()
.append("rect")
.attr("width",2)
.attr("height", 3)
.attr("x",function(datum){return datum.x}) // pay attention to this line
.attr("y",0);
d3 is implicitly iterating over each element in your data. For each datum in your data array, in this case there is a total of three datum, you are going to add a rectangle to the dom.
In the line that I tell you to pay attention to you notice that you're defining an anonymous (unnamed) function. What is that datum parameter coming from? It's implicitly being passed to your anonymous function.
So each rectangle has it's own corresponding datum {x : 1, y : 2}, {x:1, y:3}, {x:4, y:5} respectively. Each rectangle's x coordinate is defined by the respective datum.x attribute. Under the sheets, d3 is implicitly looping over the data array that you've defined. A similar approach to the example d3 code could be written as above.
for (var i = 0; i < data.length; i++)
{
d3.select("body").append("rect")
.attr("width",2)
.attr("height", 3)
.attr("x",data[i].x)
.attr("y",0);
}
This follows from the notion of data driven documents (d3). For each item added (a rectangle in the above example a piece of data is tied to it. In the above example you see that there is something kind of similar to your .x() and .y() accessor functions :
.attr("x",function(datum){return datum.x})
This function is telling d3 how to filter over the total datum that's being passed to the .attr() accessor method.
So, you need to determine which data you need to get a hold of to make your .attr("d", lineGenerator)call make sense. The difference between your.datum(data)call and the typical.data(data)call is that instead of parceling the data that's being passed to.data(data)`, the whole array is given as a single piece of data to the line generator function (similar to main_line(data), wherein it will again implicitly loop over the points to construct your path.
So, what you need to do is determine what a single datum will be defined as for your function to operate on.
I'm not going to define that as I don't seem to know quite which information you are operating on, but I would hazard a guess at something like.
.x(xAccessor)
.y(yAccessor)
function xAccessor(datum)
{
return xScale(datum._id.month);
}
function yAccessor(datum)
{
return yScale(datum.buildFixTime);
}
The way you have it set up, xValue and yValue are functions; you have to actually execute them on something to get a value back.
.x(function(d) { return main_x( xValue(d) ); })
.y(function(d) { return main_y( yValue(d) ); });
If you weren't using a scale, you could use
.x(xValue)
.y(yValue);
but only because if you pass in a function d3 executes it for you with the data as a parameter. And that only works for d3 methods that expect functions as possible input -- the scale functions expect data values as input.
I wrote a long piece work for another user last week that you may find useful, explaining methods that accept functions as parameters.

I am trying to populate a DOJO pie chart from a json array created by a url

I am trying to populate a dojo pie chart from a json array created by a url.
the url returns an array that looks like this
{"pieItems":[["IPv4 TCP",475919493840],["IPv6 TCP",37443255432],["IPv4 UDP",34595392128],["IPv6 ICMP",14496],["IPv4 ICMP",46560],["IP Other",12385112]]}
I have attempted to redo the format of the array changing it to one that looks like this
{"IPv4 TCP":[475919493840],"IPv6 TCP":[37443255432],"IPv4 UDP":[34595392128],"IPv6 ICMP":[14496],"IPv4 ICMP":[46560],"IP Other":[12385112]} .
the code I used to change the format is:
var len = responseObj.pieItems.length, i, hash = {};
for (i = 0; i < len; i++) {
hash[responseObj.pieItems[i][0]] = responseObj.pieItems[i][1];
}
After changing the format I can only populate the chart with on item by adding the series and specifying the name.
chart1.addSeries("IP Other", hash["IPv6 ICMP"])
This populates the chart with that one item but if i try to add another series for example
chart1.addSeries("IP Other", hash["IPv4 Other"])
It overwrites the chart and shows the data for IP Other instead of adding another slice.
How can I add all the items in the array into the pie chart?
Pie chart supports just one series object by definition. You should add different data points for different slices. A sketch:
chart.addSeries("IP", dojo.map(responseObj, function(p){
return {
y: p[1], // value
text: p[0] // label
};
});