I have a very similar task as D3.js nesting and rollup at same time and solution provided by #altocumulus for d3.js v3 works perfectly fine for me (tested). However, I am using d3.js v4 across my website and I am having difficulties replicating the same approach with v4 - I am not getting the same results. Perhaps, because I don't understand the sumChildren function. Please feel free to provide a better or different approach on how to restructure the loaded csv file as json with subtotals at every node level using d3.js v4. In my case, I need to have Population at the Country, State and the City levels.
Disclaimer: I have been using SO for many years and in most of the cases I got my answers from questions posted by other people, but this is my first question. In addition to this I am noob in d3.js
population.csv:
Country,State,City,Population
"USA","California","Los Angeles",18500000
"USA","California","San Diego",1356000
"USA","California","San Francisco",837442
"USA","Texas","Austin",885400
"USA","Texas","Dallas",1258000
"USA","Texas","Houston",2196000
index.html:
<!DOCTYPE html>
<html>
<head>
<title> Test D3.js</title>
</head>
<!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.17/d3.min.js"></script>
-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.4.0/d3.min.js"></script>
<body>
<script>
d3.csv("population.csv", function(error, data) {
if (error) throw error;
var nested = d3.nest()
.key(function(d) { return d.Country; })
.key(function(d) { return d.State; })
.rollup(function(cities) {
return cities.map(function(c) {
return {"City": c.City, "Population": +c.Population };
});
})
.entries(data);
// Recursively sum up children's values
function sumChildren(node) {
node.Population = node.values.reduce(function(r, v) {
return r + (v.values ? sumChildren(v) : v.Population);
},0);
return node.Population;
}
// Loop through all top level nodes in nested data,
// i.e. for all countries.
nested.forEach(function(node) {
sumChildren(node);
});
// Output. Nothing of interest below this line.
d3.select("body").append("div")
.style("font-family", "monospace")
.style("white-space", "pre")
.text(JSON.stringify(nested,null,2));
});
</script>
</body>
</html>
Results:
[
{
"key": "USA",
"values": [
{
"key": "California",
"value": [
{
"City": "Los Angeles",
"Population": 18500000
},
{
"City": "San Diego",
"Population": 1356000
},
{
"City": "San Francisco",
"Population": 837442
}
]
},
{
"key": "Texas",
"value": [
{
"City": "Austin",
"Population": 885400
},
{
"City": "Dallas",
"Population": 1258000
},
{
"City": "Houston",
"Population": 2196000
}
]
}
],
"Population": null
}
]
Desired Results:
[
{
"key": "USA",
"values": [
{
"key": "California",
"values": [
{
"City": "Los Angeles",
"Population": 18500000
},
{
"City": "San Diego",
"Population": 1356000
},
{
"City": "San Francisco",
"Population": 837442
}
],
"Population": 20693442
},
{
"key": "Texas",
"values": [
{
"City": "Austin",
"Population": 885400
},
{
"City": "Dallas",
"Population": 1258000
},
{
"City": "Houston",
"Population": 2196000
}
],
"Population": 4339400
}
],
"Population": 25032842
}
]
The v4 changelog tells us that
When used in conjunction with nest.rollup, nest.entries now returns {key, value} objects for the leaf entries, instead of {key, values}.
It is this little renaming from values to value within the leaf nodes which eventually breaks the code. Changing the helper function accordingly should get you back on track:
// Recursively sum up children's values
function sumChildren(node) {
if (node.value) {
node.values = node.value; // Ensure, leaf nodes will also have a values array
delete node.value; // ...instead of a single value
}
node.Population = node.values.reduce(function(r, v) {
return r + (v.value? sumChildren(v) : v.Population);
},0);
return node.Population;
}
Related
I'm using JSONpath to try and find data with an array of JSON objects but I'm struggling to get to the information I want. The array contains many objects similar to below where there are values for RecID throughout. If I use $..RecID I get them all when I only want the first Key.RecID of each object (with a value 1338438 in this example). Is there a way to only extract the top level Key.RecID value?
BTW I'm trying to do this in jMeter and I'm assuming JSONpath is the best way to do what I want but if there is a better way I'd be happy to hear about it.
Thanks in advance
[{
"Key": {
"RecID": 1338438
},
"Users": [{
"FullName": "Miss Burns",
"Users": {
"Key": {
"Name": "Burns",
"RecID": 1317474
}
}
},
{
"FullName": "Mrs Fisher",
"Users": {
"Key": {
"Name": "Fisher",
"RecID": 1317904
}
}
}
],
"User": {
"FullName": "Mrs Fisher",
"Key": {
"Name": "Fisher",
"RecID": 1317904
}
},
"Organisation": {
"Key": {
"RecID": 1313881
}
}
}]
How can I change the title of a loaded chart using javascript? The following doesn't work with external data
https://codepen.io/abdfahim/pen/zYOPvPx
var chart = am4core.createFromConfig({
"titles": [
{
"text": "ABCD",
"fontSize": 25,
"marginBottom": 10
}
],
"dataSource": {
"url": "https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-160/sample_data_serial.json"
},
"xAxes": [
{
"type": "CategoryAxis",
"dataFields": {
"category": "year"
}
}
],
"yAxes": [
{
"type": "ValueAxis"
}
],
"series": [
{
"type": "ColumnSeries",
"name": "Cars",
"dataFields": {
"categoryX": "year",
"valueY": "cars"
}
}
]
}, "chartdiv", am4charts.XYChart);
function changeTitle()
{
chart.titles[0].text = "New Title";
}
AmCharts v4 uses lists for the majority of its array-like objects, so using subscripts will not work. It's recommended to use the accessor methods provided by the list to get at the object you want to change, such as getIndex:
chart.titles.getIndex(0).title = "New title"
Updated codepen
Just in case some one will hit my same issue, I found this solution working for me
chart.titles.getIndex(0).text = "new title";
this is particularly handy if you are going to refresh the chart each x seconds
I'm trying to create a pie chart with a custom set of colours using Am4Charts and the createFromConfig method.
I've followed the tutorial here but the chart keeps appearing with it's default color set.
Here is a sample of the JSON I've tried:
"innerRadius": 100,
"colors": {"list": ["#ff0000", "#00ff00", "#0000ff" ]},
"data": {
"0": {
"pot": "Within 8 days",
"value": "£111,119.70",
},
"1": {
"pot": "9 - 17 days",
"value": "£225,537.73"
},
"2": {
"pot": "18+ days",
"value": "£720,279.85"
}
},
"legend": [],
"xAxes": [
{
"type": "CategoryAxis",
"title": {
"text": "pot"
},
"dataFields": {
"category": "pot",
"title": {
"text": "Month"
}
},
"renderer": {
"labels": {
"rotation": 190,
"verticalCenter": "middle",
"horizontalCenter": "left"
}
}
}
],
"series": [
{
"type": "PieSeries",
"dataFields": {
"value": "value",
"category": "pot"
},
"ticks": {
"disabled": true
},
"labels": {
"disabled": true
},
}
],
Can somebody see where I've gone wrong?
Update 2:
Fixed in 4.0.0-beta.85.
Make sure you clear your browser cache after upgrading. And feel free to contact us again if you are still experiencing this issue.
Update 1:
Response from amchart contributor/CTO Martynas Majeris (https://github.com/martynasma):
Looks like there are two issues: documentation is wrong and there's a bug that prevents it from working :)
I updated the docs. It should say this:
{
// ...
"series": [{
// ...
"colors": {
"list": [
"#845EC2",
"#D65DB1",
"#FF6F91",
"#FF9671",
"#FFC75F",
"#F9F871"
]
}
}]
}
Also, fixed bug in dev version. New version will be released within 1-2 days.
Original
This might be a bug and I have opened an issue on amchart github. I will update this once I get a response: https://github.com/amcharts/amcharts4/issues/577
By the way, I do think your configuration JSON has couple issues:
data is an array, not an object
legend is an object, not an array
This is what I used to create the pie chart demo for the opened issue:
// Create chart instance in one go
let chart = am4core.createFromConfig({
"colors": {
"list": ["#ff0000","#00ff00", "#0000ff"]
},
// Create pie series
"series": [{
"colors": ["#ff0000","#00ff00", "#0000ff"],
"type": "PieSeries",
"dataFields": {
"value": "value",
"category": "pot"
}
}],
// Add data
"data": [{
"pot": "Within 8 days",
"value": "£111,119.70"
}, {
"pot": "9 - 17 days",
"value": "£225,537.73"
}, {
"pot": "18+ days",
"value": "£720,279.85"
}],
// Add legend
"legend": {},
"innerRadius": 100
}, "chart", am4charts.PieChart);
When I select any particular field in the bar graph, all the graphs changes accordingly.
I want to introduce a heading above the graphs which should show which data is currently displayed in the graphs and the count.
So what changes should I make in my code?
var data = [{
"city": "New York",
"neighborhood": "N/A",
"hits": 200
}, {
"city": "New York",
"neighborhood": "Brooklyn",
"hits": 225
}, {
"city": "New York",
"neighborhood": "Queens",
"hits": 1
}, {
"city": "San Francisco",
"neighborhood": "Chinatown",
"hits": 268
}, {
"city": "San Francisco",
"neighborhood": "Downtown",
"hits": 22
}, {
"city": "Seattle",
"neighborhood": "N/A",
"hits": 2
}, {
"city": "Seattle",
"neighborhood": "Freemont",
"hits": 25
}];
var pieChart = dc.pieChart("#pieChart"),
rowChart = dc.rowChart("#rowChart");
var ndx = crossfilter(data),
cityDimension = ndx.dimension(function (d) {
return d.city;
}),
cityGroup = cityDimension.group().reduceSum(function (d) {
return d.hits;
}),
neighborhoodDimension = ndx.dimension(function (d) {
return d.neighborhood;
}),
neighborhoodGroup = neighborhoodDimension.group().reduceSum(function (d) {
return d.hits;
});
pieChart.width(200)
.height(200)
.slicesCap(4)
.dimension(cityDimension)
.group(cityGroup);
pieChart.filter = function() {};
rowChart.width(500)
.height(500)
.dimension(neighborhoodDimension)
.group(neighborhoodGroup);
dc.renderAll();
<div id="pieChart"> </div>
<div id="rowChart"> </div>
For displaying the current filters, you can use spans with class='reset' andclass='filter'` within the charts, as demonstrated in the annotated stock example
For displaying the counts of records filtered, you can use the dataCount widget or the numberDisplay widget.
Anything else, you'll have to implement the display itself, probably hooking the filtered event to determine when the filters have changed, and changing your own div using e.g. d3 or jQuery.
I'm trying to get a jsTree working with on demand loading of subnodes. My code is this:
jQuery('#introspection_tree').jstree({
"json_data" : {
"ajax" : {
url : "http://localhost/introspection/introspection/product"
}
},
"plugins" : [ "themes", "json_data", "ui" ]
});
The json returned from the call is
[
{
"data": "Kit 1",
"attr": {
"id": "1"
},
"children": [
[
{
"data": "Hardware",
"attr": {
"id": "2"
},
"children": [
]
}
],
[
{
"data": "Software",
"attr": {
"id": "3"
},
"children": [
]
}
]
]
}
.....
]
Each element could have a lot of children, the tree is going to be big. Currently this is loading the whole tree at once, which could take some time. What do I have to do to implement on-demand-loading of child-nodes when they are opened by the user?
Thanks in advance.
Irishka pointed me in the right direction, but does not fully resolve my problem. I fiddled around with her answer and came up with this. Using two different server functions is done only for clarity. The first one lists all products at top level, the second one lists all children of a given productid:
jQuery("#introspection_tree").jstree({
"plugins" : ["themes", "json_data", "ui"],
"json_data" : {
"ajax" : {
"type": 'GET',
"url": function (node) {
var nodeId = "";
var url = ""
if (node == -1)
{
url = "http://localhost/introspection/introspection/product/";
}
else
{
nodeId = node.attr('id');
url = "http://localhost/introspection/introspection/children/" + nodeId;
}
return url;
},
"success": function (new_data) {
return new_data;
}
}
}
});
The json data returned from the functions is like this (notice the state=closed in each node):
[
{
"data": "Kit 1",
"attr": {
"id": "1"
},
"state": "closed"
},
{
"data": "KPCM 049",
"attr": {
"id": "4"
},
"state": "closed"
},
{
"data": "Linux BSP",
"attr": {
"id": "8"
},
"state": "closed"
}
]
No static data is needed, the tree is now fully dynamic on each level.
I guess it would be nice to display by default first level nodes and then the children will be loaded on demand. In that case the only thing you have to modify is to add "state" : "closed" to the nodes whose child nodes are going to be loaded on demand.
You might wish to send node's id in ajax call so you modify your code
"json_data": {
//root elements to be displayed by default on the first load
"data": [
{
"data": 'Kit 1',
"attr": {
"id": 'kit1'
},
"state": "closed"
},
{
"data": 'Another node of level 1',
"attr": {
"id": 'kit1'
},
"state": "closed"
}
],
"ajax": {
url: "http://localhost/introspection/introspection/product",
data: function (n) {
return {
"nodeid": $.trim(n.attr('id'))
}
}
}
}
From jsTree documentation
NOTE:
If both data and ajax are set the initial tree is rendered from the data string. When opening a closed node (that has no loaded children) an AJAX request is made.
you need to set root elements as tree data on page load and then you will be able to retrieve their children with an ajax request
$("#introspection_tree").jstree({
"plugins": ["themes", "json_data", "ui"],
"json_data": {
//root elements
"data": [{"data": 'Kit 1', "attr": {"id": 'kit1'}} /*, ... */], //the 'id' can not start with a number
"ajax": {
"type": 'POST',
"data": {"action": 'getChildren'},
"url": function (node) {
var nodeId = node.attr('id'); //id="kit1"
return 'yuorPathTo/GetChildrenScript/' + nodeId;
},
"success": function (new_data) {
//where new_data = node children
//e.g.: [{'data':'Hardware','attr':{'id':'child2'}}, {'data':'Software','attr':{'id':'child3'}}]
return new_data;
}
}
}
});
See my answer to a similar question here (the old part) for more details
I spended hours on this problem. Finally i got it that way:
$("#resourceTree").jstree({
"types": {
"default": {
"icon": "fa fa-folder-open treeFolderIcon",
}
},
"plugins": ["json_data", "types", "wholerow", "search"],
"core": {
"multiple": false,
"data": {
"url" : function(node){
var url = "rootTree.json";
if(node.id === "specialChildSubTree")
url = "specialChildSubTree.json";
return url;
},
"data" : function(node){
return {"id" : node.id};
}
}
},
});
rootTree.json:
[
{
"text": "Opened root folder",
"state": {
"opened": true
},
"children": [
{
"id" : "specialChildSubTree",
"state": "closed",
"children":true
}
]
}
]
specialChildSubTree.json:
[
"Child 1",
{
"text": "Child 2",
"children": [
"One more"
]
}
]
So i mark the node that become the parent of the ajax loaded subtree with an id, i watch for in the core configuration.
NOTE:
That node must have the "state" : "closed" parameter and it must have
the parameter "children" : true.
I am using jsTree.js in version 3.3.3
Above solution is all fine. Here I am also providing similar working solution and very simple for lazy loading of nodes using ajax call vakata. When your API works like
https://www.jstree.com/fiddle/?lazy
and for getting any child nodes
https://www.jstree.com/fiddle/?lazy&id=2
for explanation and for complete solution you can have a look at https://everyething.com/Example-of-jsTree-with-lazy-loading-and-AJAX-call
<script type="text/javascript">
$(function () {
$('#SimpleJSTree').jstree({
'core' : {
'data' : {
'url' : "https://www.jstree.com/fiddle/?lazy",
'data' : function (node) {
return { 'id' : node.id };
}
}
}
});
});
</script>