Amcharts shown, but console output one error - javascript

I used Amcharts to show a chart, and I make a div for it in a Bootstrap component. Followed is my html & js code:
<fieldset>
<legend>Chart</legend>
<div class="row">
<form class="form-horizontal mb-sm line-height-3">
<div class="col-sm-3 col-md-3">
<div class="form-group">
<label for="submitStartTime" class="col-sm-3 control-label">Start Time</label>
<div class="col-sm-6">
<label id="submitStartTime"></label>
</div>
</div>
<div id="latencyChart" class="col-sm-9 col-md-9" style="height: 400px;"></div>
</form>
</div>
</fieldset>
js:
drawChart: function(graphType){
var that = this;
that.generateChartData();
this.chart.dataProvider = this.chartData;
this.chart.categoryField = "date";
this.chart.balloon.bulletSize = 5;
// listen for "dataUpdated" event (fired when chart is rendered) and call zoomChart method when it happens
this.chart.addListener("dataUpdated", that.zoomChart());
// AXES
// category
var categoryAxis = this.chart.categoryAxis;
categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
categoryAxis.minPeriod = "DD"; // our data is daily, so we set minPeriod to DD
categoryAxis.dashLength = 1;
categoryAxis.minorGridEnabled = true;
categoryAxis.twoLineMode = true;
categoryAxis.dateFormats = [{
period: 'fff',
format: 'JJ:NN:SS'
}, {
period: 'ss',
format: 'JJ:NN:SS'
}, {
period: 'mm',
format: 'JJ:NN'
}, {
period: 'hh',
format: 'JJ:NN'
}, {
period: 'DD',
format: 'DD'
}, {
period: 'WW',
format: 'DD'
}, {
period: 'MM',
format: 'MMM'
}, {
period: 'YYYY',
format: 'YYYY'
}];
categoryAxis.axisColor = "#DADADA";
// value
var valueAxis = new AmCharts.ValueAxis();
valueAxis.axisAlpha = 0;
valueAxis.dashLength = 1;
this.chart.addValueAxis(valueAxis);
// GRAPH
var graph = new AmCharts.AmGraph();
graph.title = "red line";
graph.valueField = "visits";
graph.bullet = "round";
graph.bulletBorderColor = "#FFFFFF";
graph.bulletBorderThickness = 2;
graph.bulletBorderAlpha = 1;
graph.lineThickness = 2;
graph.lineColor = "#5fb503";
graph.negativeLineColor = "#efcc26";
graph.hideBulletsCount = 50; // this makes the chart to hide bullets when there are more than 50 series in selection
this.chart.addGraph(graph);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
this.chart.addChartScrollbar(chartScrollbar);
this.chart.creditsPosition = "bottom-right";
// WRITE
this.chart.write("latencyChart");
this.chart.write("chartdiv");
},
// this method is called when chart is first inited as we listen for "dataUpdated" event
zoomChart: function() {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
this.chart.zoomToIndexes(this.chartData.length - 40, this.chartData.length - 1);
},
generateChartData: function(){
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 10);
for (var i = 0; i < 10; i++) {
// we create date objects here. In your data, you can have date strings
// and then set format of your dates using chart.dataDateFormat property,
// however when possible, use date objects, as this will speed up chart rendering.
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
var visits = Math.round(Math.random() * 40) - 20;
this.chartData.push({
date: newDate,
visits: visits
});
}
},
this.chart is a global variable in my js code, and it's already initialized. And the chart is shown in my page like below.
But Chrome console give some error info like below.
I debugged for some time and find out that the error happens in this.chart.write("latencyChart"). The error is cannot read property 'call' of undefined. Then I created a new div in this page called "chartdiv" to know whether the program can still work, and I added this.chart.write("chartdiv"); after the original one. and I found that there is no chart in "chartdiv" and the error goes on.

The issue is how you're assinging the zoomChart method to your dataUpdated event - that.zoomChart() is calling the zoomChart method, rather than assigning it to the event. You need to create a function that calls zoomChart so that it has access to your object's chart property during the event, i.e.
this.chart.addListener("dataUpdated", function() {
that.zoomChart()
});
Here's a fiddle with this fix.
Alternatively, you can use the dataUpdated event's argument object to access the chart object that way instead of fiddling with this/that/etc, for example:
this.chart.addListener("dataUpdated", that.zoomChart);
// ...
zoomChart: function(e) {
// different zoom methods can be used - zoomToIndexes, zoomToDates, zoomToCategoryValues
e.chart.zoomToIndexes(e.chart.dataProvider.length - 40, e.chart.dataProvider.length - 1);
},
Fiddle

Related

Chrome Dev tools doesn't show any leak, but Task Manager does until chrome crashes

So I have this quite CPU-consuming app: https://codepen.io/team/amcharts/pen/47c41af971fe467b8b41f29be7ed1880
It's a Canvas on which things are drawn (a lot).
HTML:
<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<div id="chartdiv" style="width:100%; height:400px"></div>
JavaScript:
/**
* ---------------------------------------
* This demo was created using amCharts 5.
*
* For more information visit:
* https://www.amcharts.com/
*
* Documentation is available at:
* https://www.amcharts.com/docs/v5/
* ---------------------------------------
*/
// Create root element
// https://www.amcharts.com/docs/v5/getting-started/#Root_element
var root = am5.Root.new("chartdiv");
// Set themes
// https://www.amcharts.com/docs/v5/concepts/themes/
root.setThemes([
am5themes_Animated.new(root)
]);
// Generate random data
var value = 100;
function generateChartData() {
var chartData = [];
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 1000);
firstDate.setHours(0, 0, 0, 0);
for (var i = 0; i < 50; i++) {
var newDate = new Date(firstDate);
newDate.setSeconds(newDate.getSeconds() + i);
value += (Math.random() < 0.5 ? 1 : -1) * Math.random() * 10;
chartData.push({
date: newDate.getTime(),
value: value
});
}
return chartData;
}
var data = generateChartData();
// Create chart
// https://www.amcharts.com/docs/v5/charts/xy-chart/
var chart = root.container.children.push(am5xy.XYChart.new(root, {
focusable: true,
panX: true,
panY: true,
wheelX: "panX",
wheelY: "zoomX",
scrollbarX:am5.Scrollbar.new(root, {orientation:"horizontal"})
}));
var easing = am5.ease.linear;
// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xAxis = chart.xAxes.push(am5xy.DateAxis.new(root, {
maxDeviation: 0.5,
groupData: false,
extraMax:0.1, // this adds some space in front
extraMin:-0.1, // this removes some space form th beginning so that the line would not be cut off
baseInterval: {
timeUnit: "second",
count: 1
},
renderer: am5xy.AxisRendererX.new(root, {
minGridDistance: 50
}),
tooltip: am5.Tooltip.new(root, {})
}));
var yAxis = chart.yAxes.push(am5xy.ValueAxis.new(root, {
renderer: am5xy.AxisRendererY.new(root, {})
}));
// Add series
// https://www.amcharts.com/docs/v5/charts/xy-chart/series/
var series = chart.series.push(am5xy.ColumnSeries.new(root, {
name: "Series 1",
xAxis: xAxis,
yAxis: yAxis,
valueYField: "value",
valueXField: "date",
tooltip: am5.Tooltip.new(root, {
pointerOrientation: "horizontal",
labelText: "{valueY}"
})
}));
series.data.setAll(data);
// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
xAxis: xAxis
}));
cursor.lineY.set("visible", false);
// Update data every second
setInterval(function () {
addData();
}, 100)
function addData() {
var lastDataItem = series.dataItems[series.dataItems.length - 1];
var lastValue = lastDataItem.get("valueY");
var newValue = value + ((Math.random() < 0.5 ? 1 : -1) * Math.random() * 5);
var lastDate = new Date(lastDataItem.get("valueX"));
var time = am5.time.add(new Date(lastDate), "second", 1).getTime();
series.data.removeIndex(0);
series.data.push({
date: time,
value: newValue
})
var newDataItem = series.dataItems[series.dataItems.length - 1];
newDataItem.animate({
key: "valueYWorking",
to: newValue,
from: lastValue,
duration: 600,
easing: easing
});
var animation = newDataItem.animate({
key: "locationX",
to: 0.5,
from: -0.5,
duration: 600
});
if (animation) {
var tooltip = xAxis.get("tooltip");
if (tooltip && !tooltip.isHidden()) {
animation.events.on("stopped", function () {
xAxis.updateTooltip();
})
}
}
}
setTimeout(function(){
xAxis.zoom(0.5, 1)
}, 1500)
After some time of running it, all Chromium browsers crash. Even though Dev tools does not show any memory leak - number of listeners, nodes and heap size remains the same (the heap might increase a bit initially but then stabilizes). But the task manager shows memory growing. Important thing - the browser window must be focused. The strange thing is that if I zoom-out the chart using scrollbar or resize window or close and open the tab, the memory could drop to a normal level. This thing happens both with dev tools opened and closed.
This does not happen on Firefox, so I believe it's some browser issue. Appreciate for any insights.
So we found out that this is indeed a Chromium issue, calling setTransform on a context (if nothing else is done) results to leak (which is not visible when profiling) and a crash. We reported it as a bug and hopefully it will be fixed. Meanwhile we are working on a workaround to avoid this situation.
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function loop() {
requestAnimationFrame(() => {
loop();
for (var j = 0; j < 10000; ++j) {
context.setTransform(0.5, 1, 1, 0.5, 1, 1);
}
});
}
loop();

How to add series on external event in amCharts v4?

I have a simple amCharts v4 chart with a function that adds some series and axes.
If I call the function from the script, the chart is displayed correctly, but if it is called externally from a button click or timeout, the legend displays but the series and axes do not. Is there something extra that needs to be done if the series is added later?
var chart = am4core.create("chartdiv", am4charts.XYChart);
chart.data = generateChartData();
chart.legend = new am4charts.Legend();
chart.cursor = new am4charts.XYCursor();
// Create axes
var dateAxis = chart.xAxes.push(new am4charts.DateAxis());
dateAxis.renderer.minGridDistance = 50;
// Create series
function createAxisAndSeries(field, name, opposite, bullet) {
var valueAxis = chart.yAxes.push(new am4charts.ValueAxis());
var series = chart.series.push(new am4charts.LineSeries());
series.dataFields.valueY = field;
series.dataFields.dateX = "date";
series.strokeWidth = 2;
series.yAxis = valueAxis;
series.name = name;
series.tooltipText = "{name}: [bold]{valueY}[/]";
var interfaceColors = new am4core.InterfaceColorSet();
}
var axisAndSeriesList = [];
function addAxisAndSeries(name) {
if (name==="Visits") {
createAxisAndSeries("visits", "Visits", false, "circle");
} else if (name==="Views") {
createAxisAndSeries("views", "Views", true, "triangle");
} else if (name==="Hits") {
createAxisAndSeries("hits", "Hits", true, "rectangle");
} else {
console.warn('what is ' + name +'?');
}
}
// generate some random data, quite different range
function generateChartData() {
var chartData = [];
var firstDate = new Date();
firstDate.setDate(firstDate.getDate() - 100);
firstDate.setHours(0, 0, 0, 0);
var visits = 1600;
var hits = 2900;
var views = 8700;
for (var i = 0; i < 15; i++) {
var newDate = new Date(firstDate);
newDate.setDate(newDate.getDate() + i);
visits += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);
hits += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);
views += Math.round((Math.random()<0.5?1:-1)*Math.random()*10);
chartData.push({date: newDate, visits: visits, hits: hits, views: views });
}
return chartData;
}
function addSeries() {
console.log('Add all 3 in the series');
addAxisAndSeries("Visits");
addAxisAndSeries("Views");
addAxisAndSeries("Hits");
}
// These work
// addAxisAndSeries("Visits");
// addAxisAndSeries("Views");
// addAxisAndSeries("Hits");
// This works
// addSeries();
// This does not work
// setTimeout(function(){
// addSeries();
// }, 3000);
// Clicking on "Add series" button does not work (from HTML)
// <input type="button" onclick="addSeries()" value="Add series" />
See sample pen: https://codepen.io/anon/pen/YdYJKy?editors=0011
You were on the right track in your answer:
The series inherit data from the chart, but apparently that ends with the script.
As you've witnessed, when adding a series dynamically, basically the chart doesn't make presumptions whether the asynchronously-added series will have its own data or will use the chart's. To have the chart continue to provide its data to newly-added series, run chart.invalidateData();.
Here's a fork of your demo that adds that to the addSeries() function:
https://codepen.io/team/amcharts/pen/bb863c597a46895f87d2b67534c353f6
Now the function works whether synchronously or asynchronously, whether via setTimeout or via the button.
The series inherit data from the chart, but apparently that ends with the script.
So chart.data might have {date: '2001-01-01', visits: 100, hits: 200, views: 300} and each series can just specify which data element to use. Once the script ends, this apparently no longer applies and each additional series must have its own data.
To get the example to work as expected, I commented out this line:
// chart.data = generateChartData(); /* works with this line, but not needed */
And added the data with each series like this:
var series = chart.series.push(new am4charts.LineSeries());
series.data = generateChartData(); // <---- new line here
series.dataFields.valueY = field;
Updated pen: https://codepen.io/anon/pen/VqyVjr?editors=0011
I'm still not clear why this data flow does not continue, but have something that works. Anyone who can shed light on why, please do.

How to limit xAxis label in Chart.Js 1.0.2?

I am trying to plot a twitter streaming ,tweet sentiment score on per minute basis using ChartJs 1.0.2 .The xlables are getting overlapped after sometime. How can i plot the graph for a limited number of xAxis Labels to avoid the overlap. I am using Apache Zeppelin and AngularJs interpreter for the plotting. The code is as follows.
lineChartData = {}; //declare an object
lineChartData.labels = []; //add 'labels' element to object (X axis)
lineChartData.datasets = []; //add 'datasets' array element to object
//FIRST GRAPH: score
var line = 0
y = [];
lineChartData.datasets.push({}); //create a new line dataset
dataset = lineChartData.datasets[line]
dataset.fillColor = "rgba(0, 0, 0, 0)";
dataset.strokeColor = "rgba(75,192,192,0.4)";
dataset.lineColor = "rgba(75,192,192,0.4)";
dataset.label = "Score"
dataset.data = []; // value data
angular.forEach(newValue, function(x) {
y.push(x._3);
if (line === 0)
lineChartData.labels.push(x._2); //adds x axis labels
})
lineChartData.datasets[line].data = y; //send new line data to dataset
//end FIRST GRAPH: score
var options = {
responsive: true,
animation: false,
multiTooltipTemplate: function(dataset) {
//console.log(dataset)
return dataset.datasetLabel+ " : " + dataset.value ;
dataset.strokeColor='red';
} ,
}
ctx = canvas.getContext("2d");
myLineChart = new Chart(ctx).Line(lineChartData, options);
var legend = myLineChart.generateLegend();
$("#legendDiv").html(legend);
//document.getElementById("legendDiv").innerHTML = legend;
})
}
if (window.L) {
initMap();
} else {
console.log('Loading Leaflet library');
var sc = document.createElement('script');
sc.type = 'text/javascript';
sc.src = 'https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.min.js';
sc.onload = initMap;
sc.onerror = function(err) { alert(err); }
document.getElementsByTagName('head')[0].appendChild(sc);
}
I can think of following ways.
Get only the data for limited time window to the variable but not get all data.
Group the data to large time point
Example the data for certain interval
BTW, It might be worth to wrap the code which convert to data to visualisation. It will be easier to change to a different chart or use different plot option.
If you don't have strong preference for chart.js, check spark-highcharts to see if it meets your plot needs, or create a similar wrapper to chart.js.

Visualize table on tooltip with amCharts

I'm novice on JavaScript, but really amazed by amCharts.
So, I ask here, after search a lot on internet: is it possible (or someone can tell me how) make a table as a tooltip on a amCharts graph?
I mean: I have a trend graph, based on "date", if I click on a date of a day, view a popup with a table of the details of the day's data.
Searching and try a lot of code, and I reach a possible solution.
So, considering that there aren't similar questions here or developed like I ask, I post my solution to share it.
You can try clicking "RUN": When you clicking on a point of graph, an HTML Table was displayed filled by data (fake value in this example).
THIS IS THE SNIPPET:
function createTable(){
var table = "<table>";
table += "<thead>";
table += "<tr>";
table +="<th> Dealer </th>";
table +="<th> Percent </th>";
table +="<th> Proportional </th>";
table +="</tr>";
table +="</thead>";
table +="<tbody>";
for(var i=0;i<200;i++){
table += "<tr>";
table +="<td> New York </td>";
table +="<td> "+Math.random();+" </td>";
table +="<td> "+Math.random();+" </td>";
table +="</tr>";
};
table += "</tbody>";
table += "</table>";
return table;
};
var chartData = [{
date: new Date(2012, 0, 1),
distance: 227,
duration: 408},
{
date: new Date(2012, 0, 2),
distance: 371,
duration: 482},
{
date: new Date(2012, 0, 3),
distance: 433,
duration: 562},
{
date: new Date(2012, 0, 4),
distance: 345,
duration: 379},
{
date: new Date(2012, 0, 5),
distance: 480,
duration: 501},
{
date: new Date(2012, 0, 6),
distance: 386,
duration: 443},
{
date: new Date(2012, 0, 7),
distance: 348,
duration: 405},
{
date: new Date(2012, 0, 8),
distance: 238,
duration: 309},
{
date: new Date(2012, 0, 9),
distance: 218,
duration: 287},
{
date: new Date(2012, 0, 10),
distance: 349,
duration: 485},
{
date: new Date(2012, 0, 11),
distance: 603,
duration: 890},
{
date: new Date(2012, 0, 12),
distance: 534,
duration: 810}];
var chart;
AmCharts.ready(function() {
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.dataProvider = chartData;
chart.categoryField = "date";
chart.marginTop = 0;
chart.autoMarginOffset = 5;
chart.balloon.showBullet = false;
// AXES
// category axis
var categoryAxis = chart.categoryAxis;
categoryAxis.parseDates = true; // as our data is date-based, we set parseDates to true
categoryAxis.minPeriod = "DD"; // our data is daily, so we set minPeriod to DD
categoryAxis.autoGridCount = false;
categoryAxis.gridCount = 50;
categoryAxis.gridAlpha = 0;
categoryAxis.gridColor = "#000000";
categoryAxis.axisColor = "#555555";
// we want custom date formatting, so we change it in next line
categoryAxis.dateFormats = [{
period: 'DD',
format: 'DD'},
{
period: 'WW',
format: 'MMM DD'},
{
period: 'MM',
format: 'MMM'},
{
period: 'YYYY',
format: 'YYYY'}];
// as we have data of different units, we create two different value axes
// Duration value axis
var durationAxis = new AmCharts.ValueAxis();
durationAxis.title = "duration";
durationAxis.gridAlpha = 0.05;
durationAxis.axisAlpha = 0;
durationAxis.inside = true;
// the following line makes this value axis to convert values to duration
// it tells the axis what duration unit it should use. mm - minute, hh - hour...
durationAxis.duration = "mm";
durationAxis.durationUnits = {
DD: "d. ",
hh: "h ",
mm: "min",
ss: ""
};
chart.addValueAxis(durationAxis);
// Distance value axis
var distanceAxis = new AmCharts.ValueAxis();
distanceAxis.title = "distance";
distanceAxis.gridAlpha = 0;
distanceAxis.position = "right";
distanceAxis.inside = true;
distanceAxis.unit = "mi";
distanceAxis.axisAlpha = 0;
chart.addValueAxis(distanceAxis);
// GRAPHS
// duration graph
var durationGraph = new AmCharts.AmGraph();
durationGraph.title = "duration";
durationGraph.valueField = "duration";
durationGraph.type = "line";
durationGraph.valueAxis = durationAxis; // indicate which axis should be used
durationGraph.lineColor = "#CC0000";
durationGraph.balloonText = "[[value]]";
durationGraph.lineThickness = 1;
durationGraph.legendValueText = "[[value]]";
durationGraph.bullet = "square";
chart.addGraph(durationGraph);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.zoomable = false;
chartCursor.categoryBalloonDateFormat = "DD";
chartCursor.cursorAlpha = 0;
chart.addChartCursor(chartCursor);
// LEGEND
var legend = new AmCharts.AmLegend();
legend.bulletType = "round";
legend.equalWidths = false;
legend.valueWidth = 120;
legend.color = "#000000";
chart.addLegend(legend);
// SET UP CLICK EVENTS
// create prerequisite properties
AmCharts.clickTimeout = 0; // this will hold setTimeout reference
AmCharts.lastClick = 0; // last click timestamp
AmCharts.doubleClickDuration = 300; // distance between clicks in ms - if it's less than that - it's a doubleckick
// let's define functions to actually do something on clicks/doubleclicks
// you will want to replace the insides of these with your own code
AmCharts.doSingleClick = function (event) {
//var div = document.getElementById("databody");
var table=createTable();
document.getElementById("databody").innerHTML=table;
//div.innerHTML = "Ciao<br />" + div.innerHTML;
}
/*AmCharts.doDoubleClick = function (event) {
var div = document.getElementById("events");
div.innerHTML = "Double Click<br />" + div.innerHTML;
}*/
// create click handler
AmCharts.myClickHandler = function (event) {
var ts = (new Date()).getTime();
if ((ts - AmCharts.lastClick) < AmCharts.doubleClickDuration) {
// it's double click!
// let's clear the timeout so the "click" event does not fire
if (AmCharts.clickTimeout) {
clearTimeout(AmCharts.clickTimeout);
}
// reset last click
AmCharts.lastClick = 0;
// now let's do whatever we want to do on double-click
AmCharts.doDoubleClick(event);
}
else {
// single click!
// let's delay it to see if a second click will come through
AmCharts.clickTimeout = setTimeout(function () {
// let's do whatever we want to do on single click
AmCharts.doSingleClick(event);
}, AmCharts.doubleClickDuration);
}
AmCharts.lastClick = ts;
}
// add handler to the chart
chart.addListener("clickGraphItem", AmCharts.myClickHandler);
// WRITE
chart.write("chartdiv");
});
body {
font-family: Verdana;
font-size: 12px;
padding: 10px;
}
#databody, #databody th, #databody td {
border: 1px solid #ccc;
padding: 10px;
}
#databody th {
font-weight: bold;
background-color: #eee;
}
div.box{
width:360px !important; width /**/:200px;
height:190px !important; height /**/: 200px;
padding: 4px;
border:1px solid #EEE; border-right:0 solid;
background:url(gradient.png) repeat-x fixed top left;
overflow:auto
}
}
<script src="http://www.amcharts.com/lib/amcharts.js" type="text/javascript"></script>
<div id="chartdiv" style="height: 362px;"></div>
<div class="box" id="databody">
</div>

Highstock charts give "Uncaught TypeError: Cannot read property 'addPoint' of undefined" error

I am using the highstock charts library for a set of 4 charts. I used the options object and literal notation as described HERE. The 4 charts have the same set of options by default (the renderCharts() function in the code bellow is responsible for that) and there is a charts type picker (the setChatType() function ) with the help of which the user can change the chart type.
See all togheter HERE.
Can anyone please tell me the cause of and solution for this error in the console:
"Uncaught TypeError: Cannot read property 'addPoint' of undefined"?
Thank you!
/* ============ CHARTS OPTIONS BEGIN ============ */
var options = {
chart : {
zoomType: 'x',
events : {
load : function () {
// set up the updating of the chart each second
var series = this.series[0];
setInterval(function () {
var x = (new Date()).getTime();
var y = Math.round(Math.random() * 100);
series.addPoint([x, y]);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text: null
},
exporting: {
enabled: false
},
// Disable navigator
navigator : {
enabled : false
},
series : [{
name : '',
data : (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(), i;
for (i = -999; i <= 0; i = i + 1) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
}())
}]
}
/* ============ CHARTS OPTIONS END ============ */
/* ============ DRAW CHARTS BEGIN ============ */
function renderCharts(){
$('div.chart-container').each(function(){
var chartId = $(this).attr('id');
var chartIdParts = chartId.split('-');
var chartIdentifier = chartIdParts[1];
//Set chart options dinamically
var chartId = "chart" + chartIdentifier;
var chart = $('#' + chartId);
var renderTo = "chartcontainer-" + chartIdentifier;
//Render Charts for each aech container
options.chart.renderTo = renderTo;
options.chart.type = 'line';
var chart = new Highcharts.StockChart(options);
});
}
function setChatType(){
// Show types list (piker)
$('.current-type').on('click', function(){
$(this).parents('div.chart-options').find('ul.type ul').addClass('clicked');
});
$('.chart-options ul ul li a').on('click', function(){
//Get piked chart type
var type = $(this).parent('li').attr('data-chart-type');
// For text and Title Capitalization
var textAndTitle = type.replace(/^[a-z]/, function(m){ return m.toUpperCase() });
// Show piked type in picker
var currSetClass = 'current-type ' + type;
$(this).parents('.chart-options').find('.current-type')
.text(textAndTitle)
.attr({
class : currSetClass,
title: textAndTitle
});
// Then Hide the types list
$('.chart-options ul ul').removeClass('clicked');
//Identify current chart container by ID
var chartCtnId= $(this).parents('div.chart').find('.chart-container').attr('id');
// Render chart again with new type
options.chart.renderTo = chartCtnId;
options.chart.type = type;
var chart = new Highcharts.StockChart(options);
});
}
/* ============ DRAW CHARTS END ============ */
$(document).ready(function(){
$("article.grid:even").addClass('left')
$("article.grid:odd").addClass('right');
// Draw charts
renderCharts();
// Set/change chart type
setChatType();
});
The solution, suggested by Pawel:
instead of
var chart = new Highcharts.StockChart(options);
use
var chart = new Highcharts.StockChart( $.extend(true, {}, options) );

Categories

Resources