How do I use a string variable in an object? - javascript

I have a string, that looks like this if I log it in the console:
0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118
I try to use it in an object for a chart, like this:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : [strTags]
}
]
}
But the strTags isn't printed (the numbers), it shows like above. How can I fix this that it shows like this:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : [0.0196078431373,0.078431372549,0.0196078431373,0.0392156862745,0.0196078431373,0.0196078431373,0.0196078431373,0.0588235294118,0.0588235294118]
}
]
}

You need to convert the String to an array first, e.g., by using split():
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : strTags.split(',')
}
]
}

If you need it to be an array of numbers then you have to parse the string to a floating point number. You can do this:
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : strTags.split(',').map(function(element, index, array) {
return parseFloat(element);
})
}
]
}

Another solution is JSON.parse
var barChartData = {
labels : ["People (2.5%)","War (2.1%)","Sharing (0.8%)","Animals (1.4%)","Friends (0.3%)"],
datasets : [
{
fillColor : "rgba(74,219,168,0.8)",
strokeColor : "rgba(56,193,145,1)",
data : JSON.parse("["+ strTags + "]");
}
]
}

Related

Uncaught TypeError: Cannot read property 'hidden' of undefined(Chart.js)

I'm trying to draw a lineChart and the Errormessage,
Uncaught TypeError: Cannot read property 'hidden' of undefined, occurs and I really don't know what am I missing.
Make canvas with id,'chart'
get the 'JsonObject' from DB using controller
(In the JsonObject, I put the chart type, 'line', and also put the JsonArray, the data)
move the data from JsonArray to Array using function 'getArray' to remove the index
set the chart configuration and make a chart.
function makeChart(year,month,name){
var chart = $('#chart'); //
var valueArray = new Array();
$.ajax({
dataType : 'json',
url : '/individual/makeChart',
data : {
'year': year,
'month': month,
'name' : name
},
async : false,
success : function(json) {
valueArray = getArray(json);
var config = {
type : json.type,
data : {
datasets : [{
borderColor : "#3e95cd",
data : ['1','2','3','4','5','6','7','8','9','10','11','12'],
label : 'region'
}, {
borderColor : "#c45850",
data : ['1','2','3','4','5','6','7','8','9','10','11','12'],
label : 'country'
}],
},
options:{
showLines:true,
legend:{
display:true,
labels:{
fontSize:15,
fontColor:"#000000",
fontStyle:"bold"
}
},
responsive : true,
scales : {
yAxes : [{
ticks : {
beginAtZero : true,
fontSize : 15,
fontColor : "#000000",
fontStyle : "bold"
}
}],
xAxes : [{
ticks : {
fontSize : 15,
fontColor : "#000000",
fontStyle : "bold"
}
}]
}
}
}
new Chart(chart,config); // the problem occurs here!
}
});
}
function getArray(json){
var a = new Array();
a = json.Data[0];
return a;
}

appcelerator : webview to show graph using HighCharts

I am developing an application which sends data to a webview and it uses highcharts to draw graph . The problem I am facing is I am using same graph to display different data series , so when I am calling the graph for 10th time , it firsts shows the y axis labels of all the previous 9 graphs , then the graph is loaded with labels of 10th graph . Any help .
<html>
<head>
<script src="./jquery.min.jsl"></script>
<script src="./highcharts.jsl"></script>
<script src="./exporting.jsl"></script>
<meta name="viewport" content="user-scalable=no">
<script>
function renderGraph(graphdata) {
var graphObj = JSON.parse(graphdata);
var chart = null;
Highcharts.setOptions({
lang : {
numericSymbols : ["K", "M", "G", "T", "P", "E"]
}
});
var change = {
0 : '$0K',
2 : '$2K',
4 : '$4K',
6 : '$6K',
8 : '$8K'
};
var xAxisLegends = graphObj.bottomLegends;
var seriesData = graphObj.seriesData;
var xAxisLegends = graphObj.bottomLegends;
//['Q2, 16', 'Q3, 16', 'Q4, 16', 'Q1, 17'];
var columnColors = ["#69C3DB", "#3a8a9f"];
var seriesData = graphObj.seriesData;
/*[{
name : 'Budget',
showInLegend : false,
data : [2, 4, 6, 8]
}, {
name : 'Utilisation',
showInLegend : false,
data : [1, 2, 3, 4]
}];*/
// variables which have diff values according to OS
var chartProperties = {};
// properties to assign to Charts's object
var graphHeight = 0;
// height of chart
var graphWidth = 0;
//Width of the column
var pointWidth;
// Separating the graph dimensions & styling properties as per OS name & version
if (graphObj.osname == "iphone") {
chartProperties = {
type : 'column',
renderTo : 'container'
};
xAxisProp = {
gridLineWidth : 0,
categories : xAxisLegends,
crosshair : true
};
yAxisProp = {
min : 0,
gridLineWidth : 0,
tickAmount : 5,
title : {
text : ' '
},
labels : {
formatter : function() {
var value = this.axis.defaultLabelFormatter.call(this);
return '$' + value;
}
}
};
pointWidth = 5;
} else if (graphObj.osname == "android") {
chartProperties = {
type : 'column',
plotBackgroundColor : null,
plotBackgroundImage : null,
plotBorderWidth : 0,
plotShadow : false,
height : 450,
marginTop : 100,
marginLeft : 120
},
xAxisProp = {
categories : xAxisLegends,
width : 800,
tickmarkPlacement : 'on',
labels : {
y : 40,
style : {
color : '#333333',
fontSize : '25',
fontFamily : 'Metropolis-Light',
opacity : '.6'
},
}
};
yAxisProp = {
gridLineWidth : 0,
min : 0,
tickAmount : 5,
offset : 60,
title : {
text : ''
},
labels : {
align : 'left',
style : {
color : '#333333',
fontSize : '28',
fontFamily : 'Metropolis-Light',
opacity : '.5'
},
formatter : function() {
var value = this.axis.defaultLabelFormatter.call(this);
return '$' + value;
}
},
};
pointWidth = 10;
if (parseInt(graphObj.osversion) >= 500 && parseInt(graphObj.osversion) <= 600) {
graphHeight = 600;
} else {
graphHeight = 630;
}
}
chart =
Highcharts.chart('container', {
chart : chartProperties,
credits : {
enabled : false
},
tooltip : {
enabled : false
},
exporting : {
enabled : false
},
title : {
text : ''
},
xAxis : xAxisProp,
yAxis : yAxisProp,
plotOptions : {
column : {
pointPadding : 0.2,
borderWidth : 0,
groupPadding : 0.38,
pointWidth : pointWidth
}
},
colors : columnColors,
series : seriesData
});
}
</script>
</head>
<body>
<div id="container" style="height: 100%; width: 100%; position : center;"></div>
</body>
Here is the function inside the controller which calls the graph using evalJS.
$.webViewPerformanceGraph.url = "/html/Performance.html";
$.webViewPerformanceGraph.addEventListener('load', function() {
$.webViewPerformanceGraph.evalJS("renderGraph('" + JSON.stringify(params) + "');");

JavaScript loop/array

I have the simple javascript code below which im initializing from a JSON Array Object using SimpleJSON java api how do I set data=dataSets[i] inside of a loop rather then hardcoding it.
var scatterChart = new Chart(ctx, {
type : 'scatter',
data : {
datasets : [
{
borderColor : window.chartColors.red,
backgroundColor : color(window.chartColors.red)
.alpha(0.2).rgbString(),
label : 'Sample1'
data : dataSets[0]
},
{
data : dataSets[1]
},
{
borderColor : window.chartColors.blue,
backgroundColor : color(window.chartColors.blue)
.alpha(0.2).rgbString(),
data : dataSets[2]
},
{
data : dataSets[3]
}, {
data : dataSets[4]
}, {
data : dataSets[5]
}, {
data : dataSets[6]
}, {
data : dataSets[7]
}, {
data : dataSets[8]
}, {
data : dataSets[9]
}, {
data : dataSets[10]
} ]`
You could also map the dataSets to an array of objects with the dataSet being the data property, then you could extend the first and the third with some extra properties:
// transform the datasets (from the api?) to the structure that you want
var dataSetsWithData = dataSets
.map(dataSet => ({ data: dataSet})) ;
// you now have an array of objects
// manually add the extra properties for the ones you're intresed in
dataSetsWithData[0] = {
// keep the original properties, in this case just "data"
...dataSetsWithData[0],
// additional properties for this particular index
borderColor : window.chartColors.red,
backgroundColor : color(window.chartColors.red)
.alpha(0.2).rgbString(),
label : 'Sample1'
};
dataSetsWithData[2] = {
// keep the original properties, in this case just "data"
...dataSetsWithData[0],
// additional properties for this particular index
borderColor : window.chartColors.blue,
backgroundColor : color(window.chartColors.blue).alpha(0.2).rgbString(),
};
var scatterChart = new Chart(ctx, {
type : 'scatter',
data : {
datasets : dataSetsWithData
}
});
You could set up your array without the data property (lets call it settings):
var settings = [
{
borderColor : window.chartColors.red,
backgroundColor : color(window.chartColors.red)
.alpha(0.2).rgbString(),
label : 'Sample1'
},
null,
{
borderColor : window.chartColors.blue,
backgroundColor : color(window.chartColors.blue)
.alpha(0.2).rgbString(),
}
];
Then we take dataSets and extend it with our settings:
var datasets = dataSets.map((data,i) => {
...(settings[i] || {}),
data
});
The upper code is ESnext so you might use this instead:
var datasets = dataSets.map(function(data,i){
return Object.assign({data:data},settings[i]);
});
Then we can draw the graph:
var scatterChart = new Chart(ctx, {
type : 'scatter',
data : { datasets }
});
you can write down as following using forEach
var dataArray=[];
dataSets.forEach(function(d,i){
var tempObj={};
tempObj["data"]=d;
if(i==0){
tempObj["borderColor"] = window.chartColors.red;
tempObj["backgroundColor"] =
color(window.chartColors.red).alpha(0.2).rgbString();
tempObj["label"] = 'Sample1';
}else if(i==2){
tempObj["borderColor"] = window.chartColors.blue;
tempObj["backgroundColor"] =
color(window.chartColors.blue).alpha(0.2).rgbString();
}
dataArray.push(tempObj);
});
var scatterChart = new Chart(ctx, {
type : 'scatter',
data : {
datasets :dataArray
}
if you wan to use for loop then,
var dataArray=[];
for(i=0;i<dataSets.length;i++){
var tempObj={};
tempObj["data"]=dataSets[i];
if(i==0){
tempObj["borderColor"] = window.chartColors.red;
tempObj["backgroundColor"] =
color(window.chartColors.red).alpha(0.2).rgbString();
tempObj["label"] = 'Sample1';
}else if(i==2){
tempObj["borderColor"] = window.chartColors.blue;
tempObj["backgroundColor"] =
color(window.chartColors.blue).alpha(0.2).rgbString();
}
dataArray.push(tempObj);
}
var scatterChart = new Chart(ctx, {
type : 'scatter',
data : {
datasets :dataArray
}

Add options to Charts.js

I cannot figure out where to put the options in Chart.js on my bar graph. (I am not a programmer.)
Here is the code that I have:
<canvas id="canvasOne" height="450" width="450"></canvas>
<script>
var barChartData = {
labels: ["test "],
datasets: [
{
fillColor: "#153b63",
data: [61]
},
{
fillColor: "#e99555",
data: [25]
}]
}
var myLine = new Chart(document.getElementById("canvasOne").getContext("2d")).Bar(barChartData);
</script>
All I want to do is hide the labels. The option to do this exists, and it's called scaleShowLabels: false, but I have no idea where to put it in the code. The documentation does not show this either.
You need to pass it as an option:
options = {
scaleShowLabels : false
};
var barChartData = {
labels : ["test "],
datasets : [
{
fillColor : "#153b63",
data : [61]
},
{
fillColor : "#e99555",
data : [25]
}
]
};
var myLine = new Chart(document.getElementById("canvasOne").getContext("2d")).Bar(barChartData, options);

I had follow someone code samples and try apply to my HighChart program but I can't get it work at all

I had follow someone code samples, but I'm new to javascript and highcharts. In fact
this program worked but only shows one month at a time, I want show all the months' data. Sorry for my English. Could you give me some advice thanks.
$(document).ready(function () {
var options = {
chart : {
renderTo : 'container',
defaultSeriesType : 'column',
rightMargin : 80
},
title : {
text : 'the scholls'
},
subtitle : {
text : 'data for 2012 years'
},
xAxis : {
title : 'months',
categories : []
},
yAxis : [{
min : 0,
title : {
text : 'students'
}
}, {
linkedTo : 0,
opposite : true
}
],
tooltip : {
formatter : function () {
return '<b>' + this.series.name + '</b><br/>' + this.x + 'Months: ' + this.y + ' students:';
}
},
legend : {
layout : 'vertical',
align : 'right',
verticalAlign : 'top',
x : -10,
y : 100,
borderWidth : 0
},
series : [{
name : "students total",
data : []
}
]
};
//get the json files
$.getJSON('http://localhost:3000/students/givemechart.json', function (data) {
yData = options.series[0].data; //Array to store data for y column
xData = options.xAxis.categories; //Array to store data for x column
xDataObj = data[3]; //only can show one months
yDataObj = data[3]; //only can show one totals
// [[5, 2], [6, 3], [8, 2]]
for (var key in xDataObj) {
xData.push((xDataObj[key].month));
console.dir(xData); //chrome console only
}
for (var key in yDataObj) {
yData.push((yDataObj[key].total));
console.dir(yData); //chrome console only
}
var chart = new Highcharts.Chart(options);
});
});
This is one of my json files.
[
{
"student" : {
"month" : 1,
"total" : 24
}
}, {
"student" : {
"month" : 2,
"total" : 27
}
}, {
"student" : {
"month" : 10,
"total" : 96
}
}, {
"student" : {
"month" : 11,
"total" : 1088
}
}, {
"student" : {
"month" : 12,
"total" : 125
}
}
]
Set Min and Max for Xaxis like this :
xAxis : {
title : 'months',
categories : [],
min: 1,
max: 12
}

Categories

Resources