I am trying to get a bubble chart to populate using ngx-charts. The problem is the swimlane documentation on it is almost non-existent and I haven't been able to find any good examples.
I have read the open source code that swimlane provides and have created what I believe are the appropriate variables in Typescript and have constructed my data points using an example line graph I found using the same tools. However the chart still appears empty on the page.
HTML:
<ngx-charts-bubble-chart
[view]="view"
[results]="bubbleDemoTempData"
[showGridLines]="showGridLines"
[legend]="showLegend"
[legendTitle]="legendTitle"
[xAxis]="showXAxis"
[yAxis]="showYAxis"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
[autoScale]="autoScale"
[scheme]="colorScheme"
[minRadius]="minRadius"
[maxRadius]="maxRadius"
(select)="onSelectBubbleInteractivePoint($event)"
*ngIf="dataTypeDisplay == 'GraphForm'"
[#fade]>
</ngx-charts-bubble-chart>
TypeScript:
view: any[] = [700, 400];
// options
showXAxis = true;
showXAxisLabel = true;
showYAxisLabel = true;
showYAxis = true;
gradient = false;
showLegend = true;
legendTitle = "Hi";
xAxisLabel = 'Number';
yAxisLabel = 'Color Value';
showGridLines = true;
autoScale=true;
minRadius = 1;
maxRadius = 1;
colorScheme = {
domain: ['#5AA454', '#A10A28', '#C7B42C', '#AAAAAA']
};
Data Points:
public multi = [
{
"name": "Germany",
"series": [
{
"name": "2010",
"value": 7300000
},
{
"name": "2011",
"value": 8940000
}
]
},
{
"name": "USA",
"series": [
{
"name": "2010",
"value": 7870000
},
{
"name": "2011",
"value": 8270000
}
]
},
{
"name": "France",
"series": [
{
"name": "2010",
"value": 5000002
},
{
"name": "2011",
"value": 5800000
}
]
}
];
I would appreciate if someone could give me some advice on correctly populating the chart.
I was eventually able to get it worked out. I will post the same 3 code snippets from above here in their updated forms.
HTML:
<ngx-charts-bubble-chart
[results]="bubbleDemoTempData"
[view]="view"
[showGridLines]="showGridLines"
[legend]="legend"
[legendTitle]="legendTitle"
[legendPosition]="legendPOsition"
[xAxis]="XAxis"
[yAxis]="YAxis"
[showXAxisLabel]="showXAxisLabel"
[showYAxisLabel]="showYAxisLabel"
[xAxisLabel]="xAxisLabel"
[yAxisLabel]="yAxisLabel"
[trimXAxisTicks]="trimXAxisTicks"
[trimYAxisTicks]="trimYAxisTicks"
[maxXAxisTickLength]="maxXAxisTickLength"
[maxYAxisTickLength]="maxYAxisTickLength"
[roundDomains]="roundDomains"
[minRadius]="minRadius"
[maxRadius]="maxRadius"
[autoScale]="autoScale"
[schemeType]="schemeType"
(select)="onSelectBubbleInteractivePoint($event)"
*ngIf="dataTypeDisplay == 'GraphForm'"
[#fade]>
</ngx-charts-bubble-chart>
TypeScript:
view: any[] = [700, 400];
// options
showGridLines = true;
legend = true;
legendTitle = "Dots Mf'er";
legendPosition = "right";
xAxis = true;
yAxis = true;
showXAxisLabel = true;
showYAxisLabel = true;
xAxisLabel = "LR";
yAxisLabel = "Jobs";
trimXAxisTicks = true;
trimYAxisTicks = true;
rotateXAxisTicks = true;
maxXAxisTickLength = 16;
maxYAxisTickLength = 16;
// xAxisTicks;
// yAxisTicks;
roundDomains = false;
maxRadius = 5;
minRadius = 5;
autoScale = true;
schemeType = "ordinal";
tooltipDisabled = false;
Data Points:
public bubbleDemoTempData = [
{
"name": "Example1",
"series": [
{
"name": "a",
"x": 0,
"y": 0,
"r": 1
},
{
"name": "b",
"x":10,
"y":3,
"r":10
}
]
},
{
"name":"Example2",
"series": [
{
"name":"1",
"x":20,
"y":1,
"r":30
},
{
"name":"2",
"x":3,
"y":3,
"r":500
}
]
}
];
This works and definitely answers my question from above. That being said the grid lines are still not appearing but that's an entirely different issue that I may have to post a new ticket for.
Related
I get an input like this:
input 1:
{
"name": "Ben",
"description": "Ben",
"attributes": [
{
"type": "Background",
"value": "Default"
},
{
"type": "Hair-color",
"value": "Brown"
}
]
}
input 2
{
"name": "Ice",
"description": "Ice",
"attributes": [
{
"type": "Background",
"value": "Green"
},
{
"type": "Hair-color",
"value": "White"
}
]
}
input 3
{
"name": "Itay",
"description": "Itay",
"attributes": [
{
"type": "Background",
"value": "Default"
},
{
"type": "Hair-color",
"value": "Brown"
}
]
}
What I want to do is count the amount of each type of background and each type of hair-color appearing.
(These are sample examples and in reality there are more types and different values)
Let's say in these examples we have 2 objects that have a background as default then I want to have a count of that like so:
export interface TraitCount {
value: string,
count: number
}
export interface CountOfEachAttribute {
trait_type: string,
trait_count: traitCount[] | null,
total_variations: number
}
I want the most effective code because there are other aspects to the code, in addition it will run on 5-10k queries not just three, so needs
to run in good times too :D
(It's similar to my other question done with python but now I need it in js also)
Atm it's something like this:
(Apart of a much bigger code so keep that in mind)
setInitalCountOfAllAttribute( state, { payload }: PayloadAction<CountOfEachAttribute[] | null> ) {
if (payload === null) {
state.countOfAllAttribute = null;
} else {
state.countOfAllAttribute = payload;
}
},
setCountOfAllAttribute(state, { payload }: PayloadAction<Attribute>) {
if (state.countOfAllAttribute !== null) {
state.countOfAllAttribute.map(
(countOfEachAttribute: CountOfEachAttribute) => {
// Find the trait type
if (countOfEachAttribute.trait_type === payload.trait_type) {
// initiate the trait count array to store all the trait values and add first trait value
if (countOfEachAttribute.trait_count === null) {
const new_trait_count = { value: payload.value, count: 1 };
countOfEachAttribute.trait_count = [new_trait_count];
countOfEachAttribute.total_variations++;
}
// Trait array already existed.
else {
// Check if value already present or not
const checkValue = (obj: any) => obj.value === String(payload.value);
const isPresent = countOfEachAttribute.trait_count.some(checkValue)
const isPresent2 = countOfEachAttribute.trait_count.find((elem: any) => elem.value === String(payload.value))
// Value matched, increase its count by one
if (isPresent2) {
countOfEachAttribute.trait_count &&
countOfEachAttribute.trait_count.map((trait) => {
if (trait.value === payload.value) {
trait.count++;
}
});
}
// Value doesn't match, add a new entry and increase the count of variations by one
else {
const new_trait_count = { value: payload.value, count: 1 };
countOfEachAttribute.trait_count = [
...countOfEachAttribute.trait_count,
new_trait_count,
];
countOfEachAttribute.total_variations++;
}
}
}
}
);
}
},
You can merge all arrays and use Array.reduce.
const input1 = {
"name": "Ben",
"description": "Ben",
"attributes": [{
"type": "Background",
"value": "Default"
},
{
"type": "Hair-color",
"value": "Brown"
}
]
}
const input2 = {
"name": "Ice",
"description": "Ice",
"attributes": [{
"type": "Background",
"value": "Green"
},
{
"type": "Hair-color",
"value": "White"
}
]
}
const input3 = {
"name": "Itay",
"description": "Itay",
"attributes": [{
"type": "Background",
"value": "Default"
},
{
"type": "Hair-color",
"value": "Brown"
}
]
}
const mergedInput = [input1, input2, input3];
const result = mergedInput.reduce((acc, item) => {
item.attributes.forEach(attrItem => {
const existType = acc.find(e => e.trait_type == attrItem.type);
if (existType) {
var existAttr = existType.trait_count.find(e => e.value == attrItem.value);
if (existAttr) {
existAttr.count++;
} else {
existType.trait_count.push({
value: attrItem.value,
count: 1
});
existType.total_variations++;
}
} else {
acc.push({
trait_type: attrItem.type,
trait_count: [{
value: attrItem.value,
count: 1
}],
total_variations: 1
})
}
});
return acc;
}, []);
console.log(result);
I suggest instead of creating an array for trait_count to make it an object so you don't have to iterate over it whenever you are adding a new attribute. In the snippet below I'm using the value of the attribute as a sort of hash that allows the access to the given property without having to call the Array.prototype.find function
const input1 = {"name":"Ben","description":"Ben","attributes":[{"type":"Background","value":"Default"},{"type":"Hair-color","value":"Brown"}]};
const input2 = {"name":"Ice","description":"Ice","attributes":[{"type":"Background","value":"Green"},{"type":"Hair-color","value":"White"}]};
const input3 = {"name":"Itay","description":"Itay","attributes":[{"type":"Background","value":"Default"},{"type":"Hair-color","value":"Brown"}]};
function countAtributes(input, totalCounts={}) {
input.attributes.forEach((attribute) => {
if (!totalCounts[attribute.type])
totalCounts[attribute.type] = {trait_type: attribute.type, trait_count: {}, total_variations: 0};
if (!totalCounts[attribute.type].trait_count[attribute.value]) {
totalCounts[attribute.type].trait_count[attribute.value] = {value: attribute.value, count: 1};
totalCounts[attribute.type].total_variations+=1;
}
else totalCounts[attribute.type].trait_count[attribute.value].count +=1;
})
}
const totalCounts = {};
countAtributes(input1, totalCounts);
countAtributes(input2, totalCounts);
countAtributes(input3, totalCounts);
console.log(totalCounts);
It could be turned into the array afterwards with Object.values if necessary
I believe it is a much better approach to what you had before as you don't have to iterate over the tables of trait_counts. In theory it should significantly reduce the time taken. Iterating over the array and checking a condition each time is much slower than key lookup in Javascript object
I keep getting this error code on different lines every time I run this script , but I can not figure out why? here is the source code. I will answer any questions and or can respond quickly . I'm not sure what other details to give.
$(function() {
var
bungieId = checkParams('bungieId'),
destinyId = checkParams('destinyId'),
joined = checkParams('joined'),
checkName = function(name, list) {
var m = false; // flag
console.log('Checking list for ' + name + '...');
// loop through clan usernames and check for a match
$.each(list, function(i) {
// make case insensitve
if (name.toLowerCase() === list[i].toLowerCase()) {
console.log('Confirmed: ' + list[i]);
m = true;
}
});
if (m) {
return true;
} else {
return false;
}
};
if (bungieId && destinyId && joined) {
$.ajax({
url: "https://www.bungie.net/Platform/Destiny2/2/Account/" + destinyId + "/Character/0/Stats/UniqueWeapons/",
headers: {
"X-API-Key": apiKey
},
success: function(data) {
if (data.ErrorStatus === 'Success') {
Telesto = data.Response.weapons[0].values.uniqueWeaponKills.basic.displayValue,
TheHuckleberry = data.Response.weapons[1].values.uniqueWeaponKills.basic.displayValue,
RatKing = data.Response.weapons[2].values.uniqueWeaponKills.basic.displayValue,
Anarchy = data.Response.weapons[3].values.uniqueWeaponKills.basic.displayValue,
SUROSRegime = data.Response.weapons[4].values.uniqueWeaponKills.basic.displayValue,
Sunshot = data.Response.weapons[5].values.uniqueWeaponKills.basic.displayValue,
DARCI = data.Response.weapons[6].values.uniqueWeaponKills.basic.displayValue,
Borealis = data.Response.weapons[7].values.uniqueWeaponKills.basic.displayValue,
Thunderlord = data.Response.weapons[8].values.uniqueWeaponKills.basic.displayValue,
PolarisLance = data.Response.weapons[9].values.uniqueWeaponKills.basic.displayValue,
Crimson = data.Response.weapons[10].values.uniqueWeaponKills.basic.displayValue,
FightingLion = data.Response.weapons[11].values.uniqueWeaponKills.basic.displayValue,
TractorCannon = data.Response.weapons[12].values.uniqueWeaponKills.basic.displayValue,
LeMonarque = data.Response.weapons[13].values.uniqueWeaponKills.basic.displayValue,
GravitonLance = data.Response.weapons[14].values.uniqueWeaponKills.basic.displayValue,
VigilanceWing = data.Response.weapons[15].values.uniqueWeaponKills.basic.displayValue,
BlackTalon = data.Response.weapons[16].values.uniqueWeaponKills.basic.displayValue,
TheColony = data.Response.weapons[17].values.uniqueWeaponKills.basic.displayValue,
SleeperSimulant = data.Response.weapons[18].values.uniqueWeaponKills.basic.displayValue,
HardLight = data.Response.weapons[19].values.uniqueWeaponKills.basic.displayValue,
Merciless = data.Response.weapons[20].values.uniqueWeaponKills.basic.displayValue,
SkyburnersOath = data.Response.weapons[21].values.uniqueWeaponKills.basic.displayValue,
PrometheusLens = data.Response.weapons[22].values.uniqueWeaponKills.basic.displayValue,
Malfeasance = data.Response.weapons[23].values.uniqueWeaponKills.basic.displayValue,
OutbreakPerfected = data.Response.weapons[24].values.uniqueWeaponKills.basic.displayValue,
Jötunn = data.Response.weapons[25].values.uniqueWeaponKills.basic.displayValue,
WishEnder = data.Response.weapons[26].values.uniqueWeaponKills.basic.displayValue,
SweetBusiness = data.Response.weapons[27].values.uniqueWeaponKills.basic.displayValue,
Coldheart = data.Response.weapons[28].values.uniqueWeaponKills.basic.displayValue,
TheWardcliffCoil = data.Response.weapons[29].values.uniqueWeaponKills.basic.displayValue,
LegendofAcrius = data.Response.weapons[30].values.uniqueWeaponKills.basic.displayValue,
Wavesplitter = data.Response.weapons[31].values.uniqueWeaponKills.basic.displayValue,
WhisperoftheWorm = data.Response.weapons[32].values.uniqueWeaponKills.basic.displayValue,
Arbalest = data.Response.weapons[33].values.uniqueWeaponKills.basic.displayValue,
TwoTailedFox = data.Response.weapons[34].values.uniqueWeaponKills.basic.displayValue,
Sturm = data.Response.weapons[35].values.uniqueWeaponKills.basic.displayValue,
Riskrunner = data.Response.weapons[36].values.uniqueWeaponKills.basic.displayValue,
IzanagisBurden = data.Response.weapons[37].values.uniqueWeaponKills.basic.displayValue,
TheChaperone = data.Response.weapons[38].values.uniqueWeaponKills.basic.displayValue,
LordofWolves = data.Response.weapons[39].values.uniqueWeaponKills.basic.displayValue,
TheProspector = data.Response.weapons[40].values.uniqueWeaponKills.basic.displayValue,
Thorn = data.Response.weapons[41].values.uniqueWeaponKills.basic.displayValue,
TheLastWord = data.Response.weapons[42].values.uniqueWeaponKills.basic.displayValue,
Cerberus = data.Response.weapons[43].values.uniqueWeaponKills.basic.displayValue,
WorldlineZero = data.Response.weapons[44].values.uniqueWeaponKills.basic.displayValue,
TheQueenbreaker = data.Response.weapons[45].values.uniqueWeaponKills.basic.displayValue,
BadJuju = data.Response.weapons[46].values.uniqueWeaponKills.basic.displayValue,
Lumina = data.Response.weapons[47].values.uniqueWeaponKills.basic.displayValue,
LegendofAcrius = data.Response.weapons[48].values.uniqueWeaponKills.basic.displayValue,
TheJadeRabbit = data.Response.weapons[49].values.uniqueWeaponKills.basic.displayValue,
AceofSpades = data.Response.weapons[50].values.uniqueWeaponKills.basic.displayValue,
TrinityGhoul = data.Response.weapons[51].values.uniqueWeaponKills.basic.displayValue,
Truth = data.Response.weapons[52].values.uniqueWeaponKills.basic.displayValue,
MIDAMultiTool = data.Response.weapons[53].values.uniqueWeaponKills.basic.displayValue;
$('#player-AceofSpades').text(AceofSpades);
$('#player-TheJadeRabbit').text(TheJadeRabbit);
$('#player-TrinityGhoul').text(TrinityGhoul);
$('#player-SweetBusiness').text(SweetBusiness);
$('#player-TheWardcliffCoil').text(TheWardcliffCoil);
$('#player-Wavesplitter').text(Wavesplitter);
$('#player-TheQueenbreaker').text(TheQueenbreaker);
$('#player-PrometheusLens').text(PrometheusLens);
$('#player-Two-TailedFox').text(Two - TailedFox);
$('#player-TheJadeRabbit').text(TheJadeRabbit);
$('#player-DARCI').text(DARCI);
$('#player-TheChaperone').text(TheChaperone);
$('#player-Lumina').text(Lumina);
$('#player-LegendofAcrius').text(LegendofAcrius);
$('#player-GravitonLance').text(GravitonLance);
$('#player-SleeperSimulant').text(SleeperSimulant);
$('#player-SkyburnersOath').text(SkyburnersOath);
$('#player-Merciless').text(Merciless);
$('#player-Thorn').text(Thorn);
$('#player-LeMonarque').text(LeMonarque);
$('#player-BlackTalon').text(BlackTalon);
$('#player-TheProspector').text(TheProspector);
$('#player-Crimson').text(Crimson);
$('#player-Borealis').text(Borealis);
$('#player-PolarisLance').text(PolarisLance);
$('#player-IzanagisBurden').text(IzanagisBurden);
$('#player-Sunshot').text(Sunshot);
$('#player-Arbalest').text(Arbalest);
$('#player-WhisperoftheWorm').text(WhisperoftheWorm);
$('#player-LegendofAcrius').text(LegendofAcrius);
$('#player-TheLastWord').text(TheLastWord);
$('#player-MIDAMulti-Tool').text(MIDAMulti - Tool);
$('#player-Wish-Ender').text(Wish - Ender);
$('#player-Jötunn').text(Jötunn);
$('#player-Malfeasance').text(Malfeasance);
$('#player-PrometheusLens').text(PrometheusLens);
$('#player-OutbreakPerfected').text(OutbreakPerfected);
$('#player-Truth').text(Truth);
$('#player-Coldheart').text(Coldheart);
$('#player-Cerberus+').text(Cerberus);
$('#player-WorldlineZero').text(WorldlineZero);
$('#player-BadJuju').text(BadJuju);
$('#player-Riskrunner').text(Riskrunner);
$('#player-Thunderlord').text(Thunderlord);
$('#player-Sturm').text(Sturm);
$('#player-LordofWolves').text(LordofWolves);
$('#player-FightingLion').text(FightingLion);
$('#player-TractorCannon').text(TractorCannon);
$('#player-VigilanceWing').text(VigilanceWing);
} else {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log(data);
}
},
error: function(data) {
alert('Uh oh, failed to load player stats! Looks like Bungie\'s doing server maintenance or having problems. Please check back again soon!');
console.log('Error loading player stats:', data);
}
});
}
});
This is the error code :
"Response": {
"weapons": [{
"referenceId": 2208405142,
"values": {
"uniqueWeaponAssists": {
"statId": "uniqueWeaponAssists",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponAssistDamage": {
"statId": "uniqueWeaponAssistDamage",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKills": {
"statId": "uniqueWeaponKills",
"basic": {
"value": 2069.0,
"displayValue": "2069"
}
},
"uniqueWeaponPrecisionKills": {
"statId": "uniqueWeaponPrecisionKills",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKillsPrecisionKills": {
"statId": "uniqueWeaponKillsPrecisionKills",
"basic": {
"value": 0.0,
"displayValue": "0%"
}
}
}
},
{
"referenceId": 2286143274,
"values": {
"uniqueWeaponAssists": {
"statId": "uniqueWeaponAssists",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponAssistDamage": {
"statId": "uniqueWeaponAssistDamage",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKills": {
"statId": "uniqueWeaponKills",
"basic": {
"value": 1529.0,
"displayValue": "1529"
}
},
"uniqueWeaponPrecisionKills": {
"statId": "uniqueWeaponPrecisionKills",
"basic": {
"value": 532.0,
"displayValue": "532"
}
},
"uniqueWeaponKillsPrecisionKills": {
"statId": "uniqueWeaponKillsPrecisionKills",
"basic": {
"value": 0.34793982995421846,
"displayValue": "35%"
}
}
}
},
{
"referenceId": 2362471601,
"values": {
"uniqueWeaponAssists": {
"statId": "uniqueWeaponAssists",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponAssistDamage": {
"statId": "uniqueWeaponAssistDamage",
"basic": {
"value": 0.0,
"displayValue": "0"
}
},
"uniqueWeaponKills": {
"statId": "uniqueWeaponKills",
"basic": {
"value": 169.0,
"displayValue": "169"
}
},
"uniqueWeaponPrecisionKills": {
"statId": "uniqueWeaponPrecisionKills",
"basic": {
"value": 57.0,
"displayValue": "57"
}
},
"uniqueWeaponKillsPrecisionKills": {
"statId": "uniqueWeaponKillsPrecisionKills",
"basic": {
"value": 0.33727810650887574,
"displayValue": "34%"
}
}
}
},
This is a Sample of the Json response Im simply trying to make the https request, and then parse it into dot notation in a java script file, and then call the objects in html.
I would say you are ether trying to access values before its been created because of asynchronous ajax or you are just not accessing the JSON correctly. I would recommend opening the chrome debugger and putting some break points in to follow the data.
My json look like this
[ {
"type": "quant",
"name": "horizontalError",
"prop": [
0.12,
12.9
]
},
{
"type": "categor",
"name": "magType",
"prop": [
"ml",
"md",
"mb"
]
}]
I have created drop-down menu using the "name" property of each object. Now I am trying to create checkboxes if the type is categor and slider if the type is quant based on the name the user chooses in the drop down menu
I have come so far but stuck here--
d3.json("hashmap.json", function(error,data) {
if(error) {console.log("error fetching data");}
var hashap = data;
var dropDown = d3.select("#sel").selectAll("option").data(hashap).enter().append("option").text(function(d) { return d.name} ).attr("value",function(d, i) {
return i;});
d3.select("#sel").on("change", function() {
var checkSlider = d3.select("#checkSlider"); // clearing previous checkbox or slider
if(hashap[this.value].type == "categor") {
console.log(hashap[this.value].prop.length);
for(var i =0; i >= hashap[this.value].prop.length; i++){
checkSlider.append("input").attr("type","checkbox");
checkSlider.append("label").text(hashap[this.value].prop[i]);
}
}
else {
checkSlider.append("input").attr("type","range").attr("min", hashap[this.value].prop[0]).attr("max", hashap[this.value].prop[1]);
checkSlider.append("label").text(hashap[this.value].name);
}
});
I have added comments in the code. Hope this helps
var hashap = [ {
"type": "quant",
"name": "horizontalError",
"prop": [
0.12,
12.9
]
},
{
"type": "categor",
"name": "magType",
"prop": [
"ml",
"md",
"mb"
]
}];
// creating drop down
var dropDown = d3.select("#dropdown").selectAll("option").data(hashap).enter().append("option").text(function(d) { return d.name} ).attr("value",function(d, i) {
return i;});
// adding onchange function
d3.select("#dropdown").on("change", function() {
var checkSlider = d3.select("#checkSlider").html(""); // clearing previous checkbox or slider
if(hashap[this.value].type == "categor") {
checkSlider.append("input").attr("type","checkbox");
checkSlider.append("label").text(hashap[this.value].name);
}
else {
checkSlider.append("input").attr("type","range").attr("min", 0).attr("max", 100);
checkSlider.append("label").text(hashap[this.value].name);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<select id="dropdown" ></select>
<div id="checkSlider"><div>
I have data.json in this format:
{
"Users": [
{
"userName": "Herbie",
"weigh-in data": [
{ "date": "2016.01.04", "weight": "114.3" },
{ "date": "2016.01.05", "weight": "114.6" },
{ "date": "2016.01.06", "weight": "114.9" }
]
},
{
"userName": "Wayne",
"weigh-in data": [
{ "date": "2016.02.01", "weight": "120.3" },
{ "date": "2016.02.05", "weight": "123.6" },
{ "date": "2016.02.06", "weight": "123.9" }
]
}
]
}
// etc., more user objects
In my application: a selection of a user is made, an ajax call gets this data, I loop thru it to get only the selected user's weigh-in data, and I'm successfully rendering this data to a table.
Now I'm trying to use the same result in a Dimple chart but Dimple evidently doesn't like my chartData array:
var dataObj = JSON.parse(jsonData);
var usersArray = dataObj.Users;
var chartData = [];
// etc. SNIP
for (var obj of usersArray) {
if (obj.userName === selUser) { // weigh-ins of the selected user only
dataRows.innerHTML = "";
for (var i = 0, j = selUserData.length; i < j; i++) {
var dataDate = selUserData[i].date;
var dataWeight = selUserData[i].weight;
chartData.push('{ "User"' + ': ' + '"'+selUser+'", ' + '"Date":' + ' ' + '"'+dataDate+'", ' + '"Weight":' + ' ' + '"'+dataWeight+'" }');
// SNIP: build rows from the data, load up the table, no problem
dataRows.innerHTML += row;
} // selUserData loop
var svg = dimple.newSvg("#chartContainer", 800, 600);
var chart = new dimple.chart(svg, chartData);
chart.setBounds(60, 30, 505, 305);
var x = chart.addCategoryAxis("x", "Date");
x.addOrderRule("Dates");
var y = chart.addCategoryAxis("y", "Weight");
y.addOrderRule("Weights");
var s = chart.addSeries("weigh-ins", dimple.plot.line);
chart.draw();
... which results in a non-chart. However, if I console.log or alert(chartData) and set the result as chartData, i.e.:
var chartData = [
{ "User": "Wayne", "Date": "2016.02.01", "Weight": "180.3" },
{ "User": "Wayne", "Date": "2016.02.05", "Weight": "123.6" },
{ "User": "Wayne", "Date": "2016.02.06", "Weight": "153.9" }
]
... then I get a chart, ergo my confusion.
Any insight greatly appreciated,
Whiskey
You're pushing the JSON into your array as strings not objects, it should be:
chartData.push({ "User": selUser, "Date": dataDate, "Weight": dataWeight });
Which has the added benefit of being much easier to read!
I am using an AJAX query to Fuseki, that I want to visualize in a D3.js collapsable tree. However Fuseki returns the JSON in a format that the D3.js code does not recognise. like this:
{
"head": {
"vars": [ "s" ]
} ,
"results": {
"bindings": [
{
"s": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#FourCheesesTopping"
},
"p": {
"type": "uri",
"value": "http://www.w3.org/2000/01/rdf-schema#subClassOf"
},
"o": {
"type": "uri",
"value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#CheeseTopping"
}
]
}
}
I need to convert this JSON into this format:
{
"name": "Pizza",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaBase",
"children": [
]
},
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#MeatTopping",
"children": [
{
"name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#HotSpicedBeefTopping"
}
]
}
]
}
]
}
I have tried taking the JSON and putting it into a new object with the correct format, but it is not working. Here is my code:
var parent = new Object();
var childArray=[];
var child = [];
function createChildObj(_children, children, depth, id, childName, parent, x, x0, y, y0){
var childObj = new Object();
childObj._children = _children;
childObj.children = children;
childObj.depth = depth;
childObj.id =id;
childObj.name = childName;
childObj.parent= parent;
childObj.x = x;
childObj.x0 = x0;
childObj.y = y;
childObj.y0 = y0;
return childObj;
};
console.log(root.length)
for (var i=0; i<root.length; i++){
var childName = root[i]["s"]["value"];
var childObj = createChildObj("children",null, 1, 2, childName, parent, 190, 190, 180, 180);
child.push(childObj);
}
parent.name = "Pizza";
parent.depth = 0;
parent.id = 3;
parent.children= child;
parent.x0 = root.x0;
parent.x = parent.x0;
parent.y0 = root.y0;
parent.y = parent.y0;
So I am aiming to have parent as the JSON object with the data in the correct format to parse to the d3. sorry its a mess, been fiddling for ages trying to learn D3, and the learning curve is steeper than I had anticipated. Any help would be great! cheers.