In my example, the data is generated randomly. After click on button, zoom type should be changed.
$(function() {
var chartOptions={
chart:{
zoomType : 'x',
events : {
load : function() {
var series = this.series[0];
var chart = this;
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y]);
chart.redraw();
}, 1000);
}
}
},
series : [{
name : 'AAPL',
data : [null]
}]
};
$('#container').highcharts('StockChart', chartOptions);
$('#button').click(function() {
var chart1 = $('#container').highcharts();
//alert(chart1.series[0].yData);
chartOptions.chart.zoomType = 'y';
$('#container').highcharts(chartOptions);
});
});
After click button, the old chart disappears but the new one is not generated.
Firebug shows TypeError: e is undefined and in the line series.addPoint([x, y]); shows series is undefined.
chartOptions is global so in the click handler, one property (zoomType) is changed and the rest should be the same.
alert(chart1.series[0].yData); shows the propery y data. So I tried:
$('#button').click(function() {
var chart1 = $('#container').highcharts();
//alert(chart1.series[0].yData);
chartOptions.chart.zoomType = 'y';
var chart2 = $('#container').highcharts(chartOptions);
chart2.series[0].setData(chart1.series[0].data);
chart2.redraw();
});
Then firebug shows chart2.series is undefined.
You cannot update zoom type in highcharts, without destroy() chart and create new instance. In other words, you should use
chart1.destroy()
var chart2 = $('#container').highcharts(chartOptions);
In case when you would like set range on any axis (zoom chart) you can use setExtremes() function http://api.highcharts.com/highstock#Axis.setExtremes()
When chartOptions or chart2.series is undefinded you need to use $.extend({},chartoptions)
$('#container').highcharts($.extend({},chartoptions);
Related
Having a hard time understanding why some objects won't return properly:
If I run console.log(obj.R) it returns "different", as expected. If I run console.log(obj.g) it just returns undefined. My goal is to return the first value of the g object, so something like console.log(obj.g[0]) and have the value "0.04600" returned.
Full function as requested:
function buildCandleStickChart_() {
CurrencyDataService.getChartData('BTC', vm_.selectedMarket).
then(function(data) {
// Set a default theme for the entire chart.
anychart.theme({
'defaultFontSettings': {
'fontSize': 12,
'fontFamily': 'Roboto'
}
});
var table = anychart.data.table();
// Map API data to table data.
dataArray = data.response.map(function(obj) {
// Format Date
var formatedDate = moment(obj.time * 1000).format('M-D HH:mm');
return [formatedDate, obj.open, obj.high, obj.low, obj.close, obj.volumeto];
});
// Add API data to table.
table.addData(dataArray);
// Map data to candlesticks.
var mapping = table.mapAs();
mapping.addField('open', 1, 'first');
mapping.addField('high', 2, 'max');
mapping.addField('low', 3, 'min');
mapping.addField('close', 4, 'last');
// Map data to volume bars.
var volMapping = table.mapAs();
volMapping.addField('value', 5);
// Get current lowest price.
var getLowestValue = _.minBy(data.response, 'low');
lowestLow = getLowestValue.low;
// Get current highest price.
var getHighestValue = _.maxBy(data.response, 'high');
highestHigh = getHighestValue.high;
// Scale down the volume bars.
var getHighestVolume = _.maxBy(data.response, 'volumeto');
var highestVolume = getHighestVolume.volumeto;
var getLowestVolume = _.minBy(data.response, 'volumeto');
var lowestVolume = getLowestVolume.volumeto;
// Initialize the chart.
var chart = anychart.stock();
candleStickChartRef = chart;
candleStickPlotRef = chart.plot(0);
// Initialize the candlesticks.
var candleSticks = chart.plot(0).candlestick(mapping);
candleSticks.name(vm_.selectedMarket);
// Toggle chart tooltip
chart.tooltip(false);
// Chart Padding
var padding = chart.padding();
padding.bottom(0);
padding.left(0);
padding.right(88);
padding.top(0);
// Chart Margins
var margin = chart.margin();
margin.bottom(-1);
margin.left(0);
margin.top(-1);
margin.right(0);
// Create custom date time scale.
var dateTimeScale = anychart.scales.dateTime();
var dateTimeTicks = dateTimeScale.ticks();
dateTimeTicks.interval(0, 0, 0, 1);
// Style the X-Axis.
var xAxis = chart.plot(0).xAxis();
xAxis.background('#FFFFFF');
xAxis.height(24);
xAxis.enabled(true);
// Adjust axis labels.
var labels = xAxis.labels();
labels.format(function(value) {
var date = new Date(value.tickValue);
var formattedDate = moment(date).format('MMM DD, HH:mm');
return formattedDate;
});
labels.width(118);
// Apply date time scale.
var scale = chart.xScale();
scale.ticks([{major: {unit: 'minute', count: 15}, minor: {unit: 'second', count: 1}}]);
// Declare the Y-Axis scale.
var yScale = chart.plot(0).yScale();
// Set the position of the Y-Axis values.
var yAxis = chart.plot(0).yAxis(0);
yAxis.orientation('right');
yAxis.drawFirstLabel(true);
yAxis.drawLastLabel(false);
// Set the position of the Y-Axis labels.
var yLabels = chart.plot(0).yAxis().labels();
yLabels.offsetX(0);
yLabels.format(function() {
return this.value.toFixed(vm_.currencySettings[vm_.selectedMarket].decimal);
});
console.log(chart.plot(0).yAxis().labels());
// Horizontal Grid Lines.
chart.plot(0).yGrid().enabled(true);
chart.plot(0).yGrid().stroke('#ced4da', 1);
// Enable current price indicator.
var indicator = chart.plot(0).priceIndicator();
// Set line settings.
indicator.value('last-visible');
indicator.fallingStroke('#ff6b6b');
indicator.fallingLabel({background: '#ff6b6b'});
indicator.risingStroke('#20c997');
indicator.risingLabel({background: '#20c997'});
indicator.label().fontColor('White');
indicator.label().fontFamily('Roboto');
// Initialize the volume bars.
var volumeBars = chart.plot(0);
var volume = volumeBars.column(volMapping).name('Volume');
volume.zIndex(1);
// Create and tune Y-Scale for volume bars.
var extraYScale = anychart.scales.linear();
extraYScale.maximum(highestVolume + (highestVolume * 4));
extraYScale.minimum(lowestVolume);
volume.yScale(extraYScale);
// Enable Legend.
var legend = chart.plot(0).legend();
legend.enabled(false);
// Set legend position.
legend.positionMode('inside');
// Style legend.
legend.position('top');
legend.align('left');
legend.background().enabled(true);
legend.background().fill('#fff', 0.87);
legend.background().stroke('#ced4da', 1);
legend.padding(8);
legend.margin(8);
legend.drag(true);
// Set listener on the chart container.
document.getElementById('chart-left').onclick = function(event) {
mouseHoverHandler_(event);
};
// Event handler to get Y-Axis value on click.
function mouseHoverHandler_(event) {
// X click coordinate on plot.
var y = event.offsetY;
// Plot bounds related to chart container.
var plotHeight = chart.plot(0).yAxis().getPixelBounds().height;
// Plot left margin
var plotTopoffset = chart.plot(0).yAxis().getPixelBounds().top;
// Click on data area.
if (y < plotTopoffset || y > plotTopoffset + plotHeight) {
return;
}
// Get value of click related to yScale.
var ratio = (y - plotTopoffset) / plotHeight;
var value = (yScale.inverseTransform(1 - ratio)).toFixed(8);
// Setting this value triggers watch which will build line.
vm_.chartSelectedSwapRate = parseFloat(value);
}
// Customize the crosshair and yLabel.
chart.crosshair(true);
chart.crosshair().xLabel(false);
chart.crosshair().yLabel().format(function() {
return Number(this.value).toFixed(8);
});
chart.crosshair().xStroke(null);
chart.crosshair().yStroke('#212529', 1);
chart.crosshair().yLabel().fontColor('#fff');
chart.crosshair().yLabel().fontSize(12);
chart.crosshair().yLabel().padding(2);
chart.crosshair().yLabel().hAlign('center');
chart.crosshair().yLabel().width(78);
chart.crosshair().yLabel().fontFamily('Roboto');
chart.crosshair().yLabel().background({
fill: '#212529',
stroke: '#212529'
});
// Toggle the timeline scroller.
chart.scroller().enabled(false);
// Configure the visual settings of the falling candlesticks.
candleSticks.fallingFill('#ff6b6b');
candleSticks.fallingStroke('#ff6b6b', 1, '0', 'round');
// Configure the visual settings of the rising candlesticks.
candleSticks.risingFill('#20c997');
candleSticks.risingStroke('#20c997', 1, '0', 'round');
// Configure the visual settings of the volume bars.
volume.normal().fill('#e9ecef');
// Set the width of candlesticks and volume bars.
chart.plot(0).pointWidth(6);
// Toggle the default contextual menu.
chart.contextMenu(false);
// Enable the custom contextual menu.
// var customContextMenu = anychart.ui.contextMenu();
// Build the custom contextual menu.
// (TODO)jberthelot: Connect these menu actions with the Go Long and Go Short sidebar
// functions.
// customContextMenu.attach(chart);
// customContextMenu.itemsFormatter(function(items) {
// items = {
// 'menu-item-1': {
// 'text': 'Create a Long Cryptoswap',
// 'action': function() {
// alert('You are going Long!');
// }
// },
// 'menu-item-2': {
// 'text': 'Create a Short Cryptoswap',
// 'action': function() {
// alert('You are going Short!');
// }
// }
// };
// return items;
// });
// Add a custom class name to the contextual menu for easier styling.
// customContextMenu.addClassName('custom-context-menu');
// Set the candlestick chart container element.
chart.container('chart-left');
// Initiate the candlestick chart display.
if (vm_.chart) {
vm_.chart.dispose();
}
vm_.chart = chart;
chart.draw();
});
}
I have created a Google Pie Chart using the following code:
var data = google.visualization.arrayToDataTable(array);
var options = {
title: 'Meta Share',
is3D: true,
sliceVisibilityThreshold: .04,
slices: { 6 : {offset: 0.2},
},
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I want to select a slice of the pie chart dynamically depending on what my user is doing.
I now have the following code:
var slice = 8;
I would now like to use this variable in the above code, however; replacing the '6' with the variable 'slice' does not work.
Any suggestions? :)
You can't use variables as keys in object literals, you'd have to first create the object, then use brackets to use the variable as a key
var slice = 8;
var slices = {};
slices[slice] = {offset: 0.2};
var data = google.visualization.arrayToDataTable(array);
var options = {
title : 'Meta Share',
is3D : true,
sliceVisibilityThreshold : .04,
slices : slices
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I have a area chart which is having a dynamic point that will be added to chart.I got this http://jsfiddle.net/rjpjwve0/
but it looks like the point gets displayed first and then after a delay the chart draws back. Now i want to display the last point which will be a animated point and it should travel with chart without delay in rendering.
Could any one help me to achieve this.
I put together a test, and it seems to work well.
I updated the load event to add a second series, using the same series.data[len -1] values; then in the setInterval portion, we update that new point at each iteration.
That way, by updating the existing marker rather than destroying one marker and creating another, the animation works as desired.
Code:
events: {
load: function () {
var series = this.series[0],
len = series.data.length;
//-------------------------------------
//added this part ->
this.addSeries({
id: 'end point',
type: 'scatter',
marker: {
enabled:true,
symbol:'circle',
radius:5,
fillColor:'white',
lineColor: 'black',
lineWidth:2
},
data: [[
series.data[len - 1].x,
series.data[len - 1].y
]]
});
var series2 = this.get('end point');
//-------------------------------------
setInterval(function () {
var x = (new Date()).getTime(),
y = Math.random();
len = series.data.length;
series.addPoint([x,y], true, true);
//and added this line -->
series2.data[0].update([x,y]);
}, 1000);
}
}
Fiddle:
http://jsfiddle.net/jlbriggs/a6pshutt/
You can try this :
series: [{
name: 'Random data',
marker : {
enabled : false,
lineWidth: 0,
radius: 0
},
data: (function () {
// generate an array of random data
var data = [],
time = (new Date()).getTime(),
i;
for (i = -19; i <= 0; i += 1) {
data.push({
x: time + i * 1000,
y: Math.random()
});
}
return data;
}())
}]
Its works.
Greg.
I'm trying to make a C3 bar plot using the X with dates. I have the data formatted already in consecutive dates aggregated by days.
I've created a fiddle with what I thought will work: https://jsfiddle.net/8aL1stcs/
the plot as such is working fine, here is a version of the fiddle with the X axis commented out: https://jsfiddle.net/8aL1stcs/1/
var elementID = "#myPlot";
var myData = {};
//myData.x = 'x';
//myData.xFormat = "%Y-%m-%d";
myData.type = 'bar';
myX = ["2015-11-20", "2015-11-21", "2015-11-22","2015-11-23", "2015-11-24"];
myY = [1,2,3,4,5];
myX.splice(0,0,'x');
myY.splice(0,0,'New Reports');
myData.columns = [];
//myData.columns.push(myX);
myData.columns.push(myY);
var chart = c3.generate({
bindto: elementID,
data: myData,
size: {
height: 480,
width:400,
},
bar: {
width: {
ratio: 0.5 // this makes bar width 50% of length between ticks
}
// or
//width: 100 // this makes bar width 100px
}
});
Basically I want to mimic this plot here:
For this, I think I need to use some automated way of handling the x-ticks. In other words: I don't want to set the ticks manually.
You missed this in your c3 generate json.
axis: {
x: {
type: 'timeseries',
tick: {
format: "%b-%d"//format in which you want the output
}
},
}
Working code here
Hope this helps!
I'm working with Nvd3 charts from the examples from their official website. Now I want a line chart to update periodically based on data sent from server but I couldn't found any useful Example for this on internet.
I have created a function which re-draws the chart when new data is arrived but i want to append every new point to the existing chart (like we can do in highcharts) but i'm stuck.
Here is the code I'm using for Updating the chart.
var data = [{
"key" : "Long",
"values" : getData()
}];
var chart;
function redraw() {
nv.addGraph(function() {
var chart = nv.models.lineChart().margin({
left : 100
})
//Adjust chart margins to give the x-axis some breathing room.
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(350) //how fast do you want the lines to transition?
.showLegend(true) //Show the legend, allowing users to turn on/off line series.
.showYAxis(true) //Show the y-axis
.showXAxis(true);
//Show the x-axis
chart.xAxis.tickFormat(function(d) {
return d3.time.format('%x')(new Date(d))
});
chart.yAxis.tickFormat(d3.format(',.1%'));
d3.select('#chart svg').datum(data)
//.transition().duration(500)
.call(chart);
nv.utils.windowResize(chart.update);
return chart;
});
}
function getData() {
var arr = [];
var theDate = new Date(2012, 01, 01, 0, 0, 0, 0);
for (var x = 0; x < 30; x++) {
arr.push({
x : new Date(theDate.getTime()),
y : Math.random() * 100
});
theDate.setDate(theDate.getDate() + 1);
}
return arr;
}
setInterval(function() {
var long = data[0].values;
var next = new Date(long[long.length - 1].x);
next.setDate(next.getDate() + 1)
long.shift();
long.push({
x : next.getTime(),
y : Math.random() * 100
});
redraw();
}, 1500);