I'm very new to Chart js and JavaScript in general so am probably doing a few thing wrong here.
I am creating a scatter plot which depending on user input could have a variable number of values.
I was wondering if there's a way to use a for loop inside the datasets rather then how I currently have all the x and y values listed?
This is my current code.
const values = ["1", "2", "3", "4", "5", "6", "7", "8"];
const data = {
datasets: [
{
data: [
{
x: values.at(0),
y: values.at(1)
},
{
x: values.at(2),
y: values.at(3)
},
{
x: values.at(4),
y: values.at(5)
},
{
x: values.at(6),
y: values.at(7)
}
],
backgroundColor: "#55c4ec"
}
]
};
const myChart = new Chart(document.getElementById("myChart"), {
type: "scatter",
data: data
});
Related
I'm getting this data from backend and need paste it in my Apex Charts chart - https://apexcharts.com/javascript-chart-demos/area-charts/spline/
{
"ADA": {
"name": "ADA",
"data": [
0,
0,
"98"
]
},
"MATIC": {
"name": "MATIC",
"data": [
"127",
"128",
"65"
]
},
"DOT": {
"name": "DOT",
"data": [
0,
"6",
"6"
]
}
}
Config looks like this with my stupid non iterate solution that works (series it's common array, inside objects with name/data)
series: [
{
name: props.portfolioGrowthData.data.chart_tokens_data.MATIC.name,
data: props.portfolioGrowthData.data.chart_tokens_data.MATIC.data.map(
(x, index) => x
),
},
{
name: props.portfolioGrowthData.data.chart_tokens_data.ADA.name,
data: props.portfolioGrowthData.data.chart_tokens_data.ADA.data.map(
(x, index) => x
),
},
{
name: props.portfolioGrowthData.data.chart_tokens_data.DOT.name,
data: props.portfolioGrowthData.data.chart_tokens_data.DOT.data.map(
(x, index) => x
),
},
],
But this solution it's not what i need because empty tokens displays in chart too and after scale of our app there gonna be a mess of tokens. Looks like i need somehow handle data from backend and iterate objects without static name and data but all my tries are failed... How can i handle it?
I have a set of data that needs to be reformatted according to a specific format that i desire.
Below is the format of data that I'm receiving.
const recieved = [
{
"name": "1PM Industries IncĀ ",
"series": [
{
"value": 0.0001,
"name": "2019-08-30"
},
{
"value": 0,
"name": "2019-08-28"
}
]
}
]
What i need to do is iterate through all object property keys "name", "series", "value" and change them to "id", "data" , "x" and "y" respectively.
Below is the format of data that i want the above data set to be changed.
I need the "name" to be replaced with "x" and "value" should be replaced with "y"
const columns = [
{
"id": "japan",
"data": [
{
"x": "plane",
"y": 45
},
{
"x": "helicopter",
"y": 253
}
]
}
]
I found out that we can access property keys of objects by Object.keys
function formatData(columns) {
columns.map(col => {
})
}
I find myself in really hard situations when it comes to formatting of data. Hope someone could help me with this. Thanks
This should work:
received.map(r => ({
id: r.name,
data: r.series.map(s => ({
x: s.name,
y: s.value
}))
}));
Map over each received object, return a new object. id of the new object is name of the received object. data of new object is a map of series of old objects converting name to x and value to y.
You could rename the properties (Assigning to new variable names) and generate new objects.
const
recieved = [{ name: "1PM Industries Inc ", series: [{ value: 0.0001, name: "2019-08-30" }, { value: 0, name: "2019-08-28" }] }],
result = recieved.map(({ name: id, series }) => ({
id,
data: series.map(({ value: x, name: y }) => ({ x, y }))
}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use map method for this.
const recieved = [
{
"name": "1PM Industries Inc ",
"series": [
{
"value": 0.0001,
"name": "2019-08-30"
},
{
"value": 0,
"name": "2019-08-28"
}
]
}
]
let output = recieved.map(o=>{
let data = o.series.map((i)=>{ return {x: i.value, y: i.name}});
return {id: o.name, data}
});
console.log(output)
you can use for..in loop in conjunction with hasOwnProperty() method
use recursion to have a better script
I have data in json format, so i want plot with plotly js, what i need is to create a plot of different states by semester, so i need to filter each state (example California), after that i need to get the mean of each semester and finally plot it.
So far i have this code, but i dont know how to filter im new in js
// Trace1
var trace1 = {
x: data.map(row => row.date),
y: data.map(row => row.snap_biannual_chan),
text: data.map(row => row.state_name),
name: "snap_biannual_chan",
type: "line"
};
// Combining both traces
var data = [trace1];
// Apply the group barmode to the layout
var layout = {
title: "Practice",
xaxis: {
categoryorder: "array",
}
};
// Render the plot to the div tag with id "plot"
Plotly.newPlot("plot", data, layout)
this is the json example:
"county_state_id": "06001",
"pop_hispan_prop": ".1176472187212034",
"pop_un_st": 3059000,
"state_name": "California",
"county_name": "Alameda County",
"pop_un_co": 109000,
"state_id": "06",
"county_id": "001",
"pop_co": 1605217,
"pop_st": 38654206,
"state_abbrev": "CA",
"semester": "0118",
"snap_beneficiaries": 102034,
"snap_biannual_chan": -2.02980374083036,
"sem": "Jan18",
"pop_un_co_per": 6.790359185082141,
"pop_un_st_per": 7.913757173022776,
"year": 2018,
"month": 1,
"date": "January2018"
You can use the array filter() and reduce() methods to calculate the mean without having to micromanage a bunch of loops and variables. Here's an example:
const data = [
{ state_id: "01", snap_biannual_chan: 5.5 },
{ state_id: "01", snap_biannual_chan: 3 },
{ state_id: "02", snap_biannual_chan: 5 }
];
const state01 = data.filter(x => x.state_id === "01");
const meanState01 = state01.reduce((acc, item) => {
acc.sum += item.snap_biannual_chan;
acc.mean = acc.sum / state01.length
return acc;
}, { sum: 0, mean: 0 });
console.log(meanState01);
console.log("the mean: ", meanState01.mean);
I have variable data having json data as below:
[
{
"BillingMonth":"11",
"BillingYear":"2016",
"Volume":"72",
"BillingMonthName":"November",
"BillingProduct":"Product1"
},
{
"BillingMonth":"11",
"BillingYear":"2016",
"Volume":"617",
"BillingMonthName":"November",
"BillingProduct":"Product2"
},
{
"BillingMonth":"12",
"BillingYear":"2016",
"Volume":"72",
"BillingMonthName":"December",
"BillingProduct":"Product1"
},
{
"BillingMonth":"12",
"BillingYear":"2016",
"Volume":"72",
"BillingMonthName":"December",
"BillingProduct":"Product2"
}
]
What I want to split above json data using javascript/jquery and get them stored in two variables data1, data2 having json data as below as result:
{
type: "stackedBar",
legendText: "Product1",
showInLegend: "true",
data1: [
{ x: November, y: 72 },
{ x: December, y: 72 },
]
}
and
{
type: "stackedBar",
legendText: "Product2",
showInLegend: "true",
data2: [
{ x: November, y: 617 },
{ x: December, y: 72 },
]
}
The above will bind in canvas js stackedbar chart.
Thanks!
Hey here's a solution I had a lot of fun working on I hope it works well for you. I wasn't sure if you would always have 2 products product1, product2 so I went with a more general approach for n amount of products. The result is in an array format, but you can use es6 destructuring to get the two variables data1 and data2 like I did below:
/*
* helper function to restructure json in the desired format
*/
function format(obj) {
var formatted = {
"type": "stackedBar",
"legendText": obj.BillingProduct,
"showInLegend": "true",
"data": [{
"x": obj.BillingMonthName,
"y": obj.Volume
}]
}
return formatted;
}
/*
* returns an array of unique products with corresponding BillingMonth/Volume data
*/
function getStackedBarData(data) {
// transform each obj in orignal array to desired structure
var formattedData = data.map(format);
// remove duplicate products and aggregate the data fields
var stackedBarData =
formattedData.reduce(function(acc, val){
var getProduct = acc.filter(function(item){
return item.legendText == val.legendText
});
if (getProduct.length != 0) {
getProduct[0].data.push(val.data[0]);
return acc;
}
acc.push(val);
return acc;
}, []);
return stackedBarData;
}
var data = [{
"BillingMonth": "11",
"BillingYear": "2016",
"Volume": "72",
"BillingMonthName": "November",
"BillingProduct": "Product1"
}, {
"BillingMonth": "11",
"BillingYear": "2016",
"Volume": "617",
"BillingMonthName": "November",
"BillingProduct": "Product2"
}, {
"BillingMonth": "12",
"BillingYear": "2016",
"Volume": "72",
"BillingMonthName": "December",
"BillingProduct": "Product1"
}, {
"BillingMonth": "12",
"BillingYear": "2016",
"Volume": "72",
"BillingMonthName": "December",
"BillingProduct": "Product2"
}]
var dataVars = getStackedBarData(data);
var data1 = dataVars[0];
var data2 = dataVars[1];
console.log(data1);
console.log(data2);
Hope this helps you!
I wanted to map data from the service call to java script object for same javascript object will be passed to the chart api
The single data format of the javascript array should be like this
var val2 = {
label: 'Data Seg2',
data: [[0, 10]]
};
it can have multiple data values also like this
var val3 = {
label: 'Data Seg2',
data: [[0, 10], [1, 20],[2, 30],[3, 40],[4, 50]]
};
Tha main Array looks like this
var datatest = [{
label: 'First Label',
data: [[0, 30]]
}, {
label: 'Second Label',
data: [[0, 20]]
}, {
label: 'Third Label',
data: [[0, 50]]
}, {
label: 'Fourth Label',
data: [[0, 10]]
}];
Now i have the service all result like this.
{"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"}
Now i want to map this result to "datatest" format
How can i do this ?
Thanks in advance
You could use jQuery.map() function like this:
var serverJSON = {"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"};
var serverData = JSON.parse(serverJSON.d);
var datatest= $.map(serverData, function(arrayItem) {
return {
label: arrayItem.label,
data: $.map(arrayItem.data, function(dataItem) {
return [[parseFloat(dataItem.Key), parseFloat(dataItem.Value)]];
})
};
});
Result is :
[{"label":"Lable1","data":[[0,108859]]},{"label":"Lable2","data":[[0,20493248.94]]},{"label":"Label3","data":[[0,1195]]}]
Working demo.
You data is a little bit strange, anyway...
var rawData = {"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"};
var dataSet = JSON.parse(rawData.d);
var fn = function(data){
data.data = data.data.map(function(d){
return [d.Key, d.Value];
});
return data;
};
var newSet = dataSet.map(fn); // what you want
Result:
[
{
"label": "Lable1",
"data": [
[
"0",
"108859"
]
]
},
{
"label": "Lable2",
"data": [
[
"0",
"20493248.94"
]
]
},
{
"label": "Label3",
"data": [
[
"0",
"1195"
]
]
}
]
It will do the trick. Not sure if there is other elegant way to do so.
PS: it is recommended to format your json string first via http://jsonformat.com/ or so
with pure JavaScript you can do this:
mapthis = {"d":"[{\"label\":\"Lable1\",\"data\":[{\"Key\":\"0\",\"Value\":\"108859\"}]},{\"label\":\"Lable2\",\"data\":[{\"Key\":\"0\",\"Value\":\"20493248.94\"}, {\"Key\":\"1\",\"Value\":\"1111111.94\"}]},{\"label\":\"Label3\",\"data\":[{\"Key\":\"0\",\"Value\":\"1195\"}]}]"};
var x = eval(mapthis.d);
var newdatatest = [];
for(var i=0; i<x.length; i++){
var datas = [];
for(var j=0; j<x[i].data.length;j++){
datas.push([x[i].data[j].Key, x[i].data[j].Value]);
}
newdatatest.push( {label:x[i].label, data:datas} );
}
console.log(JSON.stringify(newdatatest,null,2));
Results:
[
{
"label": "Lable1",
"data": [
[
"0",
"108859"
]
]
},
{
"label": "Lable2",
"data": [
[
"0",
"20493248.94"
],
[
"1",
"1111111.94"
]
]
},
{
"label": "Label3",
"data": [
[
"0",
"1195"
]
]
}
]