Retrieving data from API using Javascript - javascript

I'm trying to build a dynamic chart that updates every second off of this API data using CanvasJS: http://www.coincap.io/history/1day/BTC
I can't get the correct values to show. Right now it is only showing the first data set (MktCap) in the X axis. I need the data from the second set (Price). Am I messing up the keys?
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function() {
var dataPoints = [];
var chart;
$.getJSON("http://www.coincap.io/history/1day/BTC", function(data) {
$.each(data, function(key, value){
dataPoints.push({x: value[1][0], y: parseInt(value[1][1])});
});
chart = new CanvasJS.Chart("chartContainer",{
title:{
text:"Live Chart with dataPoints from External JSON"
},
data: [{
type: "line",
dataPoints : dataPoints,
}]
});
chart.render();
updateChart();
});
function updateChart() {
$.getJSON("http://www.coincap.io/history/1day/BTC", function(data) {
$.each(data, function(key, value) {
dataPoints.push({
x: parseInt(value[1][0]),
y: parseInt(value[1][1])
});
});
chart.render();
setTimeout(function(){updateChart()}, 1000);
});
}
}
</script>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></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>

The problem is in $.each(data, ... because data is an object, with the following shape:
{
"market_cap": [[0, 1], [1, 2], [2, 1], ...],
"price": [[0, 21], [1, 42], [2, 11], ...],
"volume": [[0, 10], [1, 3], [2, 2], ...],
}
When calling $.each over the object, it is iterating over the keys of the object. With you code, it is getting only two items of the array. What you would want to do is choose "price", so it will iterate over all of the items. For example:
$.each(data.price, function(key, value) {
dataPoints.push({
x: value[0],
y: value[1],
})
})
Both in the initial and updateChart functions. Please note that you don't need to use parseInt because it is already an integer. After that, you will see the correct line.

Related

Plotly Hides Markers on Line Chart

I'm trying to create a line chart with markers for about 30 data points using Plotly. For some reason Plotly decides to hide the markers when the data points goes above a certain threshold such as 15. There is no reason to hide them as there is more than adequate space available. See below:
var trace1 = {
x: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
y: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
type: 'line',
marker: {
size: 10,
},
};
var data = [trace1];
Plotly.newPlot('myDiv', data);
https://codepen.io/ceds/pen/OJMOjjB
Any idea how to disable this?
I am not getting the exact problem why its not showing when more than 15 data points, But i have a solution using mode: 'lines+markers' property for marker and lines, as below,
var trace1 = {
x: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
y: [1, 2, 3, 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20],
type: 'line',
mode: 'lines+markers',
marker: {
size: 10,
},
};
var data = [trace1];
Plotly.newPlot('myDiv', data);
<head>
<!-- Load plotly.js into the DOM -->
<script src='https://cdn.plot.ly/plotly-latest.min.js'></script>
</head>
<body>
<div id='myDiv'><!-- Plotly chart will be drawn inside this DIV --></div>
</body>
Hope this help.

setting color for null values plotly.js

I want to set a custom color for missing values in plotly javascript and cannot figure out how.
In the following example the missing value is represented by null in the array given to the color property.
<script src="https://cdn.plot.ly/plotly-latest.js" ></script>
<div id="myDiv" style="width:100%;height:100%" ></div>
<script>
var color_scale = [[0, "#ff0000"], [1, "#00ff00"]];
var trace = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
marker: {
color: [1, 2, 3, null],
colorscale: color_scale
},
mode: 'markers',
type: 'scatter'
};
var data = [trace];
Plotly.newPlot('myDiv', data);
</script>
If I understand correctly, you want to break out of the defined color-scale from #ff0000 to #00ff00?
in the marker.color-array, you can also specify strings, which can contain any way of defining a color: hex-notation, name, rgb, ...
So this should be along the lines of what you are looking for:
color: [1,2,3,'#0000ff'],

Highstock graph showing data outside selected range

I have an implementation of a Highstock graph where the chart is narrowed in width in order to fit two of them side by side. A consequence of this seems to be some data bleeding over from the left graph to the right. Even when there is only one graph narrowed in width by itself it seems to still happen.
The data that bleeds over cannot be seen unless you hover over it. The halo and tooltip appear for the data point despite being outside of the selected range in the navigator.
Hovering over a point outside of the graph
JSFiddle: http://jsfiddle.net/7dk6g6rh/
var stockChart = Highcharts.stockChart('container', {
xAxis: {
width: '500',
type: 'datetime'
},
series: [{
data: [1, 2, 3, 4, 5, 3, 4, 6, 3, 8],
pointStart: Date.UTC(2004, 3, 1),
pointInterval: 3600 * 1000
}]
});
stockChart.xAxis[0].setExtremes(1080777600000, 1080806400000);
<div id="container" style="height: 400px; min-width: 600px"></div>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript" src="https://www.highcharts.com/samples/data/usdeur.js"></script>
I solved this problem by extending Highcharts to behave how I wanted it to. I wrapped the Tooltip, Point, and Axis functions (refresh, setState, and drawCrosshair respectively) to make some checks before proceeding to normal operation.
Here is the JSFiddle with the correct behavior: http://jsfiddle.net/7dk6g6rh/7/
(function (H) {
H.wrap(H.Tooltip.prototype, 'refresh', function(proceed, points) {
for(var i=0; i<points.length; i++) {
if(!points[i].isInside) {
this.hide();
return;
}
}
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
});
H.wrap(H.Point.prototype, 'setState', function(proceed, state) {
if(this.isInside || state !== 'hover') {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
}
});
H.wrap(H.Axis.prototype, 'drawCrosshair', function(proceed) {
var hoverPoint = this.chart.hoverPoint;
if(hoverPoint && hoverPoint.isInside) {
proceed.apply(this, Array.prototype.slice.call(arguments, 1));
} else {
this.hideCrosshair();
}
});
}(Highcharts));
var stockChart = Highcharts.stockChart('container', {
xAxis: {
width: '500',
type: 'datetime'
},
series: [{
data: [1, 2, 3, 4, 5, 3, 4, 6, 3, 8],
pointStart: Date.UTC(2004, 3, 1),
pointInterval: 3600 * 1000
}]
});
stockChart.xAxis[0].setExtremes(1080777600000, 1080806400000);
<div id="container" style="height: 400px; min-width: 600px"></div>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script type="text/javascript" src="https://www.highcharts.com/samples/data/usdeur.js"></script>

Easiest Way to AutoRefresh Google Charts embeded within a page

I have two files, one outputting data from a MySQL database and one drawing a Google Graph within a page with other metrics:
grab_twitter_stats.php Output:
[15, 32], [14, 55], [13, 45], [12, 52], [11, 57], [10, 55], [9, 58], [8, 42], [7, 44], [6, 40], [5, 54], [4, 52], [3, 60], [2, 71], [1, 43],
index.php Output:
<div id="curve_chart" style="width: 900px; height: 500px">
<script type="text/javascript">
google.charts.load('current', {packages: ['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Minutes', 'Tweets'],
<?php require('grab_twitter_stats.php');?>
]);
var options = {
title: 'Tweets in last 15 Minutes',
curveType: 'function',
hAxis: {
title: 'Last 15 Minutes',
direction: '-1'
},
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</div>
This draws a graph that shows tweets in the last 15 minutes. I can get the graph to appear once, but upon trying to load a SetInterval, it does not refresh the Google Graph on the interval. I have tried wrapping the entire drawChart() function in it, and it doesn't seem to be working. I tried using AJAX but it is not formatted in JSON so ajax doesn't like it. Any suggestions on the easiest way to make this graph auto refresh?
although not JSON, you can still use ajax, even with plain text
something like this should get you close...
google.charts.load('current', {
callback: function () {
drawChart();
setInterval(drawChart, (15 * 60 * 1000));
function drawChart() {
$.ajax({
url: 'grab_twitter_stats.php',
type: 'get',
success: function (txt) {
// check for trailing comma
if (txt.slice(-1) === ',') {
txt = txt.substring(0, txt.length - 1);
}
var txtData = JSON.parse('[["Minutes", "Tweets"],' + txt + ']');
var data = google.visualization.arrayToDataTable(txtData);
var options = {
title: 'Tweets in last 15 Minutes',
curveType: 'function',
hAxis: {
title: 'Last 15 Minutes',
direction: '-1'
},
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
});
}
},
packages: ['corechart']
});

Javascript flot not showing data series

I'm using flot to display some data on a bar graph. But my data isn't displaying for some reason, and I have no idea why.
My data series is correct as far as I can see, but it still won't show.
JsFiddle: http://jsfiddle.net/9jhpyne4/1/
Code:
var plotData = [
[1, 12.35],
[2, 34.6],
[3, 56.7],
[4, 4.35]
];
$.plot($("#main-chart"), plotData, {
bars: {
show: true,
lineWidth: 0,
fill: true,
fillColor: {
colors: [{
opacity: 0.8
}, {
opacity: 0.1
}]
}
}
});
Data which you pass to plot function needs to have some metadata (like label and color):
var data = [
[1, 12.35],
[2, 34.6],
[3, 56.7],
[4, 4.35]
];
var dataset = [{ label: "a label", data: data, color: "red" }];
https://jsfiddle.net/9jhpyne4/3/
The console throw an error regarding your #main-chart width & height as invalid.
Changing your width & height from percentage to pixel based seems to fixed the error.
HTML
<div id="main-chart" style="width:200px;height:200px;"></div>
Here's your updated fiddle
You need to specify the width and height.
<div id="main-chart" style="width:200px;height:200px;"></div>
And You need to change a little your plotData variable to:
var plotData = [
[[1,0], [1, 12.35]],
[[2,0], [2, 34.6]],
[[3,0], [3, 56.7]],
[[4,0], [4, 4.35]]];
You can see a complete example here: here

Categories

Resources