How to create an object on the loop - javascript

I' am using http://canvasjs.com/ to make a chart for my website. I want to create a dynamic dataPoints using the for loop. The dataPoints will be used a variable to the canvasjs function to plot the chart. Below are my sample data and my code.
Sample:
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55},
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14}
]
}
My current code
This code doesn't throw any error. All I see on the screen is just white area. All the values are passed correcting. I' am guess its the way I have structured the DataPoints. Please help.
DataPoints = [];
for (year = 1; year <= years; year++){
inflatedClosing = $('#lookup-table-preserved #row-' + year + ' .inflated-closing').text();
if( year === years ){
DataPoints.push({x: year, y: inflatedClosing});
} else {
DataPoints.push({x: year, y: inflatedClosing});
}
}
It should look like this

Here you have a working example with all the info you give:
var DataPoints = [], years = 3;
for (var year = 1; year <= years; year++){
var inflatedClosing = parseInt($('#lookup-table-preserved #row-' + year + ' .inflated-closing').text(), 10);
DataPoints.push({x: year, y: inflatedClosing, label : year});
}
//console.log(DataPoints);
var chart = new CanvasJS.Chart("chartContainer", {
theme: "theme2",//theme1
title:{
text: "Title"
},
animationEnabled: true,
data: [
{
// Change type to "bar", "area", "spline", "pie",etc.
type: "line",
dataPoints: DataPoints
}
]
});
chart.render();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="lookup-table-preserved">
<ul id="row-1">
<li class="inflated-closing">50</li>
</ul>
<ul id="row-2">
<li class="inflated-closing">100</li>
</ul>
<ul id="row-3">
<li class="inflated-closing">200</li>
</ul>
</div>
<div id="chartContainer" style="height: 300px; width: 100%; margin-top: 20px;"></div>

Related

Update tooltip data without reloading whole chart in Canvasjs

I want to update my Tooltip in my canvas js Chart without reloading the whole chart.
let arr = this.graph_arr;
let a = [];
let b = [];
arr.map((val) => {
val.data.map((val2) => {
b.push({
x: new Date(val2.date),
y: val2.revenue,
cn: val2.check_in,
rp: val2.rev_par,
arr: val2.avrr,
adr: val2.avg_daily_rate,
date: moment(val2.date).format('Do, MMMM'),
day: moment(val2.date).format('dddd')
})
})
a.push({
type: "spline",
name: val.channel_img.split('.')[0].toUpperCase(),
markerSize: 1,
showInLegend: true,
dataPoints: b,
label: val.channel_img,
})
b = [];
})
let chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
theme: "light2",
axisY2: {
valueFormatString: "1'%'"
},
axisY: {
suffix: "%"
},
axisX: {
gridThickness: 1,
valueFormatString: "DD/MMM"
},
legend: {
cursor: "pointer",
itemclick: this.toogleDataSeries
},
toolTip: {
shared: false,
content: this.selected == 'arr' ?
`<div style='\"'width: 210px;'\"'>ARR: {arr}, date: {date} </div>` :
this.selected == 'adr' ?
`<div style='\"'width: 210px;'\"'>ARR: {arr}, date: {date] </div>` : null,
cornerRadius: '8'
},
data: a
});
chart.render();
I have this Custom Tooltip. I want to change data in it from a dropdown without reloading. Currently I am using ternary operator and reloading chart. I want to change Tooltip content without reloading when user select from dropdown.
You can programmatically show toolip by using showAtX method. Below is an example:
var chart = new CanvasJS.Chart("chartContainer", {
title:{
text: "Show Tooltip based on dropdown"
},
data: [
{
type: "column",
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}
]
});
chart.render();
var xVal = document.getElementById("xVal");
//Pass dataPoints as option to drop-down
for(var i=0; i<chart.options.data[0].dataPoints.length;i++){
var xValOption = document.createElement("option");
xValOption.text = chart.options.data[0].dataPoints[i].x = chart.options.data[0].dataPoints[i].x;
xVal.appendChild(xValOption);
}
xVal.addEventListener( "change", showTooltip);
//
function showTooltip(e){
if(xVal.value)
chart.toolTip.showAtX(Number(xVal.value));
else
chart.toolTip.hide();
}
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 360px; width: 80%; float: left"></div>
<div style="float: right; width: 15%">
Show Tooltip for <select id="xVal">
<option>Select</option>
</select>
</div>

CanvasJS: How to label axisX by week starting on Saturday?

I'm using CanvasJS to create a stacked bar chart by week. Our weeks start on Saturday, but CanvasJS seems to default to weeks starting on Sunday. Thus, the labels for this chart start on 11/3 rather than 11/2 as I need.
I found this post on the CanvasJS forum which suggests that setting minimum and maximum might help, but when I tried that, it merely shifted the plot area (as you'd expect), but the labels still reflect Sundays, not Saturdays
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
title:{
text: "Evening Sales of a Restaurant"
},
axisX: {
intervalType: "week",
interval: 1
},
data: [
{
type: "stackedBar",
dataPoints: [
{ x: new Date("11/2/2019"), y: 71 },
{ x: new Date("11/9/2019"), y: 55},
{ x: new Date("11/16/2019"), y: 50 },
{ x: new Date("11/23/2019"), y: 65 },
{ x: new Date("11/30/2019"), y: 95 }
]
},
{
type: "stackedBar",
dataPoints: [
{ x: new Date("11/2/2019"), y: 20 },
{ x: new Date("11/9/2019"), y: 35},
{ x: new Date("11/16/2019"), y: 30 },
{ x: new Date("11/23/2019"), y: 45 },
{ x: new Date("11/30/2019"), y: 25 }
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
</div>
</body>
</html>
From CanvasJS:
It’s not possible to control the starting point of label, as of now.
We will reconsider this behaviour in future releases.
https://canvasjs.com/forums/topic/how-to-label-axisx-by-week-starting-on-saturday/

Show loading image when Chart is loading

I am using a CanvasJs chart. The chart is working fine. The Chart is taking time to load. I wanted to show a loading image until the chart loads. CanvasJs charts have no defined attributes for this. Any help is appreciated.
Html:
JS:
chart = CanvasJS.Chart("chartContainer1", {});
You can add loader-image(gif) or some text within the chart-container div so that image/text is shown in the div till the chart is initialized.
setTimeout(function(){
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Basic Column Chart"
},
data: [
{
type: "column",
dataPoints: [
{ x: 10, y: 71 },
{ x: 20, y: 55 },
{ x: 30, y: 50 },
{ x: 40, y: 65 },
{ x: 50, y: 95 },
{ x: 60, y: 68 },
{ x: 70, y: 28 },
{ x: 80, y: 34 },
{ x: 90, y: 14 }
]
}
]
});
chart.render();
},2000);
img{
display: block;
margin: auto;
}
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 250px; width: 100%;">
<img src="https://i.imgur.com/fXUIBfi.gif" alt="Chart will Render Here..."/>
</div>

Dynamically Add Data Points To Rickshaw Graph

So I'm using the Rickshaw graphing library and I was wondering how to dynamically add points to a graph.
I have a graph instantiated like this:
#seriesData = [ [], [], [] ]
random = new Rickshaw.Fixtures.RandomData(150)
for (var i = 0; i < 50; i++) {
random.addData(self.seriesData)
}
#graph = new Rickshaw.Graph(
element: document.getElementById("chart")
width: 550
height: 300
renderer: 'area'
series: [
{
color: "#c05020"
data: self.seriesData[0]
name: 'One'
}, {
color: "#30c020"
data: self.seriesData[1]
name: 'Two'
}, {
color: "#2791d7"
data: self.seriesData[2]
name: 'Three'
}
]
)
#graph.render()
hoverDetail = new Rickshaw.Graph.HoverDetail(
graph: self.graph
)
legend = new Rickshaw.Graph.Legend(
graph: self.graph
element: document.getElementById('legend')
)
shelving = new Rickshaw.Graph.Behavior.Series.Toggle(
graph: self.graph
legend: legend
)
axes = new Rickshaw.Graph.Axis.Time(
graph: self.graph
)
axes.render()
And I have data coming in through socket.io like this:
app.on('data',
(one, two, three) =>
// Dynamically add data points to graph
)
And I was wondering how to append these three points to the graph. I can't find any good documentation for this library. I know it's built on top of d3.js, but I'm not sure how to incorporate these methods into my graph.
Any help would be appreciated.
I envision two scenario that could solve your question:
Using the fixed Window Series for Streaming Data
leveraging the fact that arrays in javascript are passed by reference. A demo is available here
.
var data = [
{
data: [ { x: 0, y: 120 }, { x: 1, y: 890 }, { x: 2, y: 38 }, { x: 3, y: 70 }, { x: 4, y: 32 } ],
color: "#c05020"
}, {
data: [ { x: 0, y: 80 }, { x: 1, y: 200 }, { x: 2, y: 100 }, { x: 3, y: 520 }, { x: 4, y: 133 } ],
color: "#30c020"
}
];
var graph = new Rickshaw.Graph( {
element: document.getElementById("chart"),
renderer: 'line',
height: 300,
width: 800,
series: data
} );
var y_ticks = new Rickshaw.Graph.Axis.Y( {
graph: graph,
orientation: 'left',
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis'),
} );
graph.render();
$('button#add').click(function() {
data.push({
data: [ { x: 0, y: 200 }, { x: 1, y: 390 }, { x: 2, y: 1000 }, { x: 3, y: 200 }, { x: 4, y: 230 } ],
color: "#6060c0"
});
graph.update();
});

Adding data to empty rickshaw chart

I am charting different data with RickshawJS. But I need a way to update the chart when a user clicks the #search button. Right now it just creates a new chart below the old one, and that is pretty messy.
The user enters the page and enters some details and clicks the button to chart it. So ideally I'd like to start with an empty chart that isn't shown, but I can't really figure out how to remove the data from the chart and axes and then update it.
I could call $('#chart svg').remove(); on the chart and axes but it seems messy.
$('#search').click(function(event){
event.preventDefault();
var data = utils.malletData();
var graph = new Rickshaw.Graph( {
element: document.querySelector("#chart"),
width: 800,
height: 250,
series: [ {
name: data['name'],
color: 'steelblue',
data: data['series']
} ]
} );
graph.render();
var hoverDetail = new Rickshaw.Graph.HoverDetail( {
graph: graph,
xFormatter: function(x) {
var date = new Date(x).getTime();
return moment(x).format('MMMM Do YYYY, h:mm:ss a');
},
yFormatter: function(y) { return Math.floor(y) + " users" }
} );
var xAxis = new Rickshaw.Graph.Axis.X( {
graph: graph,
orientation: 'bottom',
element: document.getElementById('x_axis'),
tickFormat: function(x) { return moment(x).fromNow(); },
ticks: 7,
tickSize: 1,
} );
xAxis.render();
var ticksTreatment = 'glow';
var yAxis = new Rickshaw.Graph.Axis.Y( {
graph: graph,
orientation: 'left',
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
ticksTreatment: ticksTreatment,
element: document.getElementById('y_axis'),
} );
yAxis.render();
});
There's no official way to do so. However, you could leverage the fact that arrays in javascript are passed by reference and then update the graph.
Have a look at this demo on fiddle
var data = [
{
data: [ { x: 0, y: 120 }, { x: 1, y: 890 }, { x: 2, y: 38 }, { x: 3, y: 70 }, { x: 4, y: 32 } ],
color: "#c05020"
}, {
data: [ { x: 0, y: 80 }, { x: 1, y: 200 }, { x: 2, y: 100 }, { x: 3, y: 520 }, { x: 4, y: 133 } ],
color: "#30c020"
}
];
var graph = new Rickshaw.Graph( {
element: document.getElementById("chart"),
renderer: 'line',
height: 300,
width: 800,
series: data
} );
var y_ticks = new Rickshaw.Graph.Axis.Y( {
graph: graph,
orientation: 'left',
tickFormat: Rickshaw.Fixtures.Number.formatKMBT,
element: document.getElementById('y_axis'),
} );
graph.render();
$('button#add').click(function() {
data.push({
data: [ { x: 0, y: 200 }, { x: 1, y: 390 }, { x: 2, y: 1000 }, { x: 3, y: 200 }, { x: 4, y: 230 } ],
color: "#6060c0"
});
graph.update();
});

Categories