why my highchart code is not working? - javascript

I have this in my drilldown event of highcharts which works right.
if (!e.seriesOptions) {
var s=e.point.name;
var chart = this,
drilldowns = {
'SAR': {
name: 'SAR',
data: yearData,
}
},
series = drilldowns[e.point.name];
chart.addSeriesAsDrilldown(e.point, series);
}
but when I replace string 'SAR' with e.point.name
if (!e.seriesOptions) {
var s=e.point.name;
var chart = this,
drilldowns = {
s: {
name: s,
data: yearData,
}
},
series = drilldowns[e.point.name];
chart.addSeriesAsDrilldown(e.point, series);
}
it does not show any drilldown data where in e.point.name has got string 'SAR' in it.

You cannot create a JS-Object like you intent to do:
var s = 'SAR',
drilldowns = {
s: {
name: s,
data: [],
}
}
will create an object drilldown with the key s instead of SAR:
{s: {name: "SAR", data: [] }}
You can however use a String for a key with bracket notation:
var s = 'SAR',
drilldowns = {};
drilldowns[s] = {
name: s,
data: []
}
will create an drilldown-object with the right keys for you:
{SAR: {name: "SAR", data: []}}

Related

how do i use the numbers i key in from a form as the input data for chartjs

i am trying to use my input data as the data of the graph
i am using chartjs
please help
iv tried to split and join the numbers but nothing is showing
i am using flask as my back end
var Diadata = []
function getdata() {
Diadata[0] = document.getElementById('Carat').value;
Diadata[1] = document.getElementById("Cut").value;
Diadata[2] = document.getElementById("Color").value;
Diadata[3] = document.getElementById("Clarity").value;
Diadata[4] = document.getElementById("Depth").value;
Diadata[5] = document.getElementById("Table").value;
Diadata[6] = document.getElementById("X").value;
Diadata[7] = document.getElementById("Y").value;
Diadata[8] = document.getElementById("Z").value;
console.log("TEST: ",[Diadata.join(" ").replace(/ /g,",")])
}
var ctxL = document.getElementById("barChartHorizontal").getContext('2d');
var myLineChart = new Chart(ctxL, {
type: 'horizontalBar',
data: {
labels: ["Carat", "Cut", "Color", "Clarity", "Depth", "Table", "X", "Y", "Z"],
datasets: [
{
label: "Price",
data: [Diadata.join(" ").replace(/ /g,",")], //i want to add my input data here
backgroundColor: 'orange',
borderWidth: 0,
}
]
},
The data array is expecting an array with values so if you remove your join it should work.
You would get this:
var Diadata = []
function getdata() {
Diadata[0] = document.getElementById('Carat').value;
Diadata[1] = document.getElementById("Cut").value;
Diadata[2] = document.getElementById("Color").value;
Diadata[3] = document.getElementById("Clarity").value;
Diadata[4] = document.getElementById("Depth").value;
Diadata[5] = document.getElementById("Table").value;
Diadata[6] = document.getElementById("X").value;
Diadata[7] = document.getElementById("Y").value;
Diadata[8] = document.getElementById("Z").value;
}
getdata();
var ctxL = document.getElementById("barChartHorizontal").getContext('2d');
var myLineChart = new Chart(ctxL, {
type: 'horizontalBar',
data: {
labels: ["Carat", "Cut", "Color", "Clarity", "Depth", "Table", "X", "Y", "Z"],
datasets: [
{
label: "Price",
data: Diadata, //i want to add my input data here
backgroundColor: 'orange',
borderWidth: 0,
}
]
},

Charting with chartjs, can't get it working correctly

I'm using chart.js#2.9.4/dist/Chart.min.js.
I have an array (data) of objects that looks like this:
(4) […]
​
0: Object { Num: "5", "Label1": "6,342", "Label2": "3,051", … }
​
1: Object { Num: "6", "Label3": "6,247", "Label4": "3,042", … }
This array has 9 objects in it. I have another array (xLabels) with 9 entries in it for the Y axis.
Any help would really be appreciated!
Here's what my code looks like right now:
for(i=1 ; i < Object.keys(data[0].length; i++) {
datasets.push( {
str = Object.entries(data[1])[i][1]
label: Object.entries(data[1])[i][0],
data: parseFloat(str.replace(/,/g, '.'))
})
}
new Chart(ctx, {
type: 'line',
datasets: [
{
labels: tLabels,
data: datasets,
}],
}
replace your for loop with this:
data.forEach((dataObject) => {
const data = Object.values(dataObject)
const label = data.shift()
data.map((entry) => (parseFloat(entry.toString().replace(/,/g, '.'))))
datasets.push({
label,
data
})
});
and your new Chart with this:
new Chart(ctx, {
type: 'line',
data: {
labels: xLabels,
datasets
}
})
example of whats happening in console:

Chartist.js Array with data

I am creating a chart with Chartist.js. I'm getting json data with the Google embed API. I have a problem with this one. The array works with the values I give. But it does not work for data from json.
my code :
var TotalBrowser = [];
var BrowserSeries = [];
var oxyn = {
queryAnalytics: function() {
var id = '164690638';
var expressions = [{
expression: 'ga:hits'
}];
var dimension = [{
name: 'ga:browser'
}];
oxyn.getReportQuery(id, '7daysago', 'today', expressions, dimension).then(function(response) {
var formattedJson = JSON.stringify(response.result, null, 2);
var data = JSON.parse(formattedJson);
var i = 0;
BrowserTotal = data.reports[0].data.totals[0].values[0];
jQuery(data.reports[0].data.rows).each(function() {
if (i <= 3) {
jQuery('#Browsers').append(browsericon[i] + this.dimensions[0]);
var percent = (parseInt(this.metrics[0].values[0]) / parseInt(BrowserTotal)) * 100;
BrowserSeries.push(Math.round(percent));
TotalBrowser.push(Math.round(percent) + '%');
i++;
}
});
demo.initChartist();
});
}
}
var demo = {
initChartist: function() {
var dataPreferences = {
series: [
[BrowserSeries.join()]
]
};
var optionsPreferences = {
donut: true,
donutWidth: 40,
startAngle: 0,
total: 100,
showLabel: false,
axisX: {
showGrid: false
}
};
Chartist.Pie('#chartPreferences', dataPreferences, optionsPreferences);
Chartist.Pie('#chartPreferences', {
labels: [TotalBrowser.join()],
series: [BrowserSeries.join()]
});
console.log(BrowserSeries.join());
}
};
it does not work that way. But if I write the code like this, it works.
Chartist.Pie('#chartPreferences', {
labels: [TotalBrowser.join()],
series: [30, 70]
});
and this is working.
Chartist.Pie('#chartPreferences', {
labels: [TotalBrowser[0], TotalBrowser[1]],
series: [BrowserSeries[0], BrowserSeries[1]]
});
console output
console.log(BrowserSeries.join());
30,70
JSON Source
It's a very silly problem.
yes I finally solved it. I write for those who have the same problem.
Chartist.Pie('#chartPreferences', {
labels: TotalBrowser,
series: BrowserSeries
});
We need to remove [ ] characters. We must also send the data directly to the array.
Also : https://github.com/gionkunz/chartist-js/issues/738

Chart.js : Is there a way to name each bubble in chart?

I have created a bubble chart using chart.js,which looks like the below
Is there a way to name each and every bubble in the chart? I am planning to put a data box below this chart. On clicking each bubble data box should display info associated with each bubble. Each bubble will have its own data like maturity_date,bond_type,credit_rating,symbol,etc... How can I name each bubble? These bubbles are created dynamically. This is the code I use to create the chart
$(document).ready(function(){
$.ajax({url: "xxxxxxxx.x.xx", success: function(result){
var dataObj = {};
dataObj.datasets = [];
var object = {};
object.label = 'First Dataset';
object.backgroundColor = [];
object.hoverBackgroundColor = [];
object.data = [];
var resultData = result.data;
var currentYear = new Date().getFullYear();
for (var i=0; i<resultData.length; i++) {
if(resultData[i].hasOwnProperty("maturity_date") && resultData[i].hasOwnProperty("ask_ytm")) {
var maturity_date = resultData[i].maturity_date.split("-");
var matYear = new Date(maturity_date[1]+"-"+maturity_date[0]+"-"+maturity_date[2]).getFullYear();
if (resultData[i].bond_type == "Tax Free" )
{
object.backgroundColor.push("#34A10C");
object.hoverBackgroundColor.push("#34A10C");
}
else
{
object.backgroundColor.push("#1130E8");
object.hoverBackgroundColor.push("#1130E8");
}
object.data.push({x: (matYear - currentYear), y: resultData[i].ask_ytm, r: 4});
}
}
dataObj.datasets.push(object);
var ctx = document.getElementById("myChart");
var myBubbleChart = new Chart(ctx,{
type: 'bubble',
data : dataObj,
legend: {
display: false
},
responsive: true,
maintainAspectRatio: true,
}
});
}});
});
In your data declaration, you can add custom properties if you need to :
data: [{
x: 20,
y: 30,
r: 15,
symbol: "£",
bond_type: "corporate"
}, {
x: 40,
y: 10,
r: 10,
symbol: "$",
bond_type: "james"
} /* ... */]
Since this data is dynamic, you need to do it from your back-end of course.
Afterwards, you can access these new properties in your callback (onClick event for instance) :
options: {
onClick: function(e) {
var element = this.getElementAtEvent(e);
if (element.length > 0) {
var data = this.config.data.datasets[element[0]._datasetIndex].data[element[0]._index];
console.log(data);
// You can have the following for instance :
// data -> { x:40, y:10, r:10, symbol:"$", bond_type:"james" }
}
}
}

Search for element in json object to update/add some data in this object

I need to search for an element in a json object like this:
var new_a = 'new';
var json = { cells:
[ { type: 'model',
id: '5aef826a1809',
attrs: {
text: 'first',
a: 'changethis'
}
},
{ type: 'model',
id: '2c11b8bd8112',
attrs: {
text: 'second'
}
}
]
}
Now I want to find the object with the id = 5aef826a1809, because I want to change the value of a to new_a or insert an a-element if it doesn't exist.
If id = 2c11b8bd8112 a new a-element with the content new_a should be added.
I tried to use
var res = _.find(json.cells, { id: '5aef826a1809' }); // doesn't work
res.attrs.a = new_a; // this would update or add new field, right?
But this doesn't work
Try like this
var new_a = 'new';
var json = {
cells: [{
type: 'model',
id: '5aef826a1809',
attrs: {
text: 'first',
a: 'changethis'
}
}, {
type: 'model',
id: '2c11b8bd8112',
attrs: {
text: 'second'
}
}]
};
var obj = json.cells.find(function (x) {
return x.id == '5aef826a1809'
});
if (obj) { // return value if found else return undefined if not found
obj.attrs.a = new_a;
console.log(json);
}
JSFIDDLE
Using this simple for loop should work, if that's what you're looking for:
for(var i = 0; i<json.cells.length; i++){
if(json.cells[i].id == "5aef826a1809" || json.cells[i].id == "2c11b8bd8112"){
json.cells[i].attrs.a = "new_a";
}
}
Hope it helped.
You can use Array.prototype.some for searching, changing and for making a short circuit to prevent more iteration than necessary.
var new_a = 'new',
json = {
cells: [{
type: 'model',
id: '5aef826a1809',
attrs: {
text: 'first',
a: 'changethis'
}
}, {
type: 'model',
id: '2c11b8bd8112',
attrs: {
text: 'second'
}
}]
};
function change(id) {
json.cells.some(function (a) {
var i = id.indexOf(a.id);
if (~i) {
a.attrs = a.attrs || {};
a.attrs.a = new_a;
id.splice(i, 1);
if (!id.length) {
return true;
}
}
});
}
change(['5aef826a1809', '2c11b8bd8112']);
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');

Categories