my graph didn't load up. I try to parse JSON from an JSP page to HTML page with javascript.
I don't know what is the problem. This is the details :
My HTML Page :
<!DOCTYPE html>
<html>
<head>
<title>Google Chart with jsp Mysql Json</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var obj="";
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
url : 'getDataGlucose.jsp',
dataType:'json',
success : function(glucoseData) {
obj = JSON.stringify(glucoseData)
alert('Pass? : '+obj);
},
error : function(xhr, type) {
alert('server error occoured')
}
});
var google_data = {
"cols": [{
"type": "number"
}, {
"type": "number"
}],
rows: []
};
for (var i = 0; i < obj.length; i++) {
google_data.rows.push({
c: [{
v: obj[i].xValue
}, {
v: obj[i].glucose
}]
});
}
var data = new google.visualization.DataTable(google_data);
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
var options = {
title: 'Glucose Data Intake',
hAxis: {
title: 'Intake'
},
curveType: 'function',
vAxis: {
title: 'mmHg'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data,options);
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My generate JSON from JSP page :
[{"glucose":5.5,"xValue":0}, {"glucose":6.2,"xValue":1}, {"glucose":5.8,"xValue":2}, {"glucose":7,"xValue":3}, {"glucose":6,"xValue":4}, {"glucose":7.5,"xValue":5}, {"glucose":6,"xValue":6}, {"glucose":5.5,"xValue":7}, {"glucose":6,"xValue":8}, {"glucose":5.8,"xValue":9}]
Found my way out. I changed from :
obj = JSON.stringify(glucoseData);
to
obj = eval('(' + JSON.stringify(glucoseData) + ')');
Related
I am using Datatables to create Highcharts. Everything functions as intended, however I am not sure how to extract the X axis title from Column 1. (Data1, Data2, Data3, Data4, Data5 etc.). I am not sure what am I missing in my code. Any advice would be appreciated because I don't know much about Javascript. Thanks in advance.
The chart should look like this.
See screenshot below.
Link to code - http://live.datatables.net/muvoyacu/2/edit
$(document).ready(function() {
var table = $("#example_full2").DataTable({
searching:false,
lengthChange: false,
ordering: false,
info: false,
paging: false,
} );
//var salary = getSalaries(table);
var salary = getRow(table,0);
var salary2 = getRow(table, 1);
var salary3 = getRow(table, 2);
var salary4 = getRow(table, 3);
var salary5 = getRow(table, 4);
// Declare axis for the column graph
var axis = {
id: "salary",
min: 0,
title: {
text: "Number"
}
};
// Declare inital series with the values from the getSalaries function
var series = {
name: "2012",
data: Object.values(salary)
};
var series2 = {
name: "2013",
data: Object.values(salary2)
};
var series3 = {
name: "2014",
data: Object.values(salary3)
};
var series4 = {
name: "2015",
data: Object.values(salary4)
};
var series5 = {
name: "2016",
data: Object.values(salary5)
};
var myChart = Highcharts.chart("container", {
chart: {
type: "column"
},
title: {
text: "Test Data"
},
xAxis: {
categories: Object.keys(salary)
},
yAxis: axis,
series: [series, series2, series3, series4, series5]
});
// On draw, get updated salaries and refresh axis and series
table.on("draw", function() {
salary = getSalaries(table);
myChart.axes[0].categories = Object.keys(salary);
myChart.series[0].setData(Object.values(salary));
});
});
function getSalaries(table) {
var salaryCounts = {};
var salary = {};
}
function getRow(table, row) {
var chart = {};
var data = table.row(row).data();
for (i=1; i<data.length; i++) {
var x = $( table.column( i ).header() ).html();
var y = data[i].replace(/[^0-9.]/g, "") * 1;
chart[x] = y;
}
return chart;
}
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<meta charset=utf-8 />
</head>
<body>
<div id="container" style=" width: 100%; height: 400px;"></div>
<div class="container">
<table id="example_full2" class="display nowrap" width="100%"><thead>
<tr><th>Year</th><th>2012</th><th>2013</th><th>2014</th><th>2015</th><th>2016</th><th>2017</th><th>2018</th><th>2019</th><th>2020</th><th>2021</th></tr></thead>
<tr ><td> Data1</td><td>3,823</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data2</td><td>800</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data3</td><td>900</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data4</td><td>200</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data5</td><td>300</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
<tr ><td> Data6</td><td>400</td><td>3,823</td><td>3,954</td><td>3,959</td><td>3,955</td><td>3,956</td><td>3,843</td><td>3,699</td><td>3,472</td><td>3,551</td></tr>
</tbody></table>
I am trying to display JSON data on a doughnut chart using chartJS. My issue is that it will only display one piece of data from the JSON. How do I get all pieces of data to display? Code is below:
const xmlhttp = new XMLHttpRequest();
const url = 'https://api.npoint.io/c189874f4d8f7c14d816';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
const datapoints = JSON.parse(this.responseText);
var labels1 = datapoints.activePositions.map(function(e) {
return e.positions;
});
var data1 = datapoints.activePositions.map(function(e) {
return e.holders;
});
const insitutionalholders = document.getElementById('institutional_activepositions_piechart').getContext('2d');
const insitutionalholdersforstock = new Chart(insitutionalholders, {
type: 'doughnut',
data: {
labels: labels1,
datasets: [{
label: 'yooooo',
data: data1,
backgroundColor: [
'rgba(0, 255, 255, 0.2)'
],
borderColor: [
'rgba(0, 255, 255, 1)'
],
borderWidth: 2.5
}]
}
});
}
}
Below is my JSON data (the data is need is from "activePositions"):
{
"activePositions": [
{
"positions": "Increased Positions",
"holders": "1,799",
"shares": "201,837,184"
},
{
"positions": "Decreased Positions",
"holders": "2,313",
"shares": "226,754,389"
},
{
"positions": "Held Positions",
"holders": "306",
"shares": "8,979,550,845"
},
{
"positions": "Total Institutional Shares",
"holders": "4,418",
"shares": "9,408,142,418"
}
],
"newSoldOutPositions": [
{
"positions": "New Positions",
"holders": "122",
"shares": "55,880,226"
},
{
"positions": "Sold Out Positions",
"holders": "74",
"shares": "8,818,741"
}
]
}
html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="draftfortesting.css">
</head>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
<body>
<div class="myChartDiv">
<canvas id="institutional_activepositions_piechart"></canvas>
</div>
</body>
<script src="AAPLpiechart.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.9.1/dist/chart.min.js"></script>
What's weird to me is that the data that shows is the third piece inside the JSON, so I'm not sure why that's happened.
The issue seems to be related to the value of holders field of data points.
The are not numbers having the "comma" (for instance "holders": "1,799",)
You could try to remove the comma and parsing as float:
var labels1 = datapoints.activePositions.map(function(e) {
return e.positions;
});
var data1 = datapoints.activePositions.map(function(e) {
return parseFloat(e.holders.replace(',','')); // remove comma
});
EDIT: to remove the "total" item:
const activePositions = datapoints.activePositions.filter(e => !e.positions.startsWith('Total'));
var labels1 = activePositions.map(function(e) {
return e.positions;
});
var data1 = activePositions.map(function(e) {
return parseFloat(e.holders.replace(',',''));
});
I am getting a json data from rest api and i want to use it as input to ZingFeed.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
function getNewData()
{
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept:"application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function(data){
var mem = data.mem.size/10000;
return mem/10000;
//$("#processInfo").append(data.mem.size);
//$("#processInfo").append(" ")
}
});
//return parseInt(memSize);
}
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
var tick = {};
// tick.plot0 = parseInt(10 + 900 * Math.random(), 10);
tick.plot0 = parseInt(getNewData());
//tick.plot0 = parseInt(1);
callback(JSON.stringify(tick));
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>
</html>
It is working fine when seen in firebug.The data (i.e mem in this case is really huge, so i have divided it twice before assigning it to tick.plot0).
After getting assigned to tick.plot0 .. it shows Nan when hovered over in the developer tools.
Could you help me plotting these huge values in ZingFeed Charts
Thanks in advance
The issue here is the nature of asynchronous functions in Javascript. Returning the data from AJAX doesn't work the way you've attempted above. You can read more about it here.
Here's a working solution.
I work on the ZingChart team. Let me know if you have other questions about the ZingChart library.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src='http://cdn.zingchart.com/zingchart.min.js'></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<script>
var chartData = {
"type":"line",
"refresh": {
"type": "feed",
"transport": "js",
"url": "feed()",
"interval": 200
},
"series":[
{
"values":[]
}
]
};
window.onload = function() {
zingchart.render({
id: "chartDiv",
data: chartData,
height: 600,
width: "100%"
});
};
window.feed = function(callback) {
$.ajax({
type: "GET",
dataType: "json",
headers: {
Accept: "application/json",
"Access-Control-Allow-Origin": "*"
},
url: "/PerformanceMonitor/showProcessUsage/chrome",
success: function (data) {
var mem = data.mem.size/10000;
var tick = {
plot0: parseInt(mem)
};
callback(JSON.stringify(tick));
}
});
};
</script>
<div id="processInfo"></div>
<div id='chartDiv'></div>
</body>
I'm newbie with D3 and NVD3 charts.
I'm trying to create a line chart, and at the end of each line, I want to display the final values.
Something like this:
http://bl.ocks.org/ZJONSSON/3918369
or fix the tooltip legend to show at the end, like this:
This is my example:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>NVD3</title>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="lib/d3.v3.js"></script>
<link href="nv.d3.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="nv.d3.js"></script>
<script type="text/javascript">
var dados = [
{ descricao: 'serie 1', valores: [
{ data: '2014-10-01T03:00:00.000Z', valor: 1 },
{ data: '2014-10-02T03:00:00.000Z', valor: 2 },
{ data: '2014-10-03T03:00:00.000Z', valor: 3 },
{ data: '2014-10-04T03:00:00.000Z', valor: 4 },
{ data: '2014-10-05T03:00:00.000Z', valor: 2 },
{ data: '2014-10-06T03:00:00.000Z', valor: 10 },
{ data: '2014-10-07T03:00:00.000Z', valor: 5 },
]},
{ descricao: 'serie 2', valores: [
{ data: '2014-10-01T03:00:00.000Z', valor: 3 },
{ data: '2014-10-02T03:00:00.000Z', valor: 2.7 },
{ data: '2014-10-03T03:00:00.000Z', valor: 5 },
{ data: '2014-10-04T03:00:00.000Z', valor: 4.6 },
{ data: '2014-10-05T03:00:00.000Z', valor: 5 },
{ data: '2014-10-06T03:00:00.000Z', valor: 5.8 },
{ data: '2014-10-07T03:00:00.000Z', valor: 7 },
]}
];
/*These lines are all chart setup. Pick and choose which chart features you want to utilize. */
nv.addGraph(function() {
var chart = nv.models.lineChart()
.useInteractiveGuideline(true) //We want nice looking tooltips and a guideline!
.transitionDuration(300) //how fast do you want the lines to transition?
.color(d3.scale.category10().range())
.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 //Chart x-axis settings
.axisLabel('Data')
.ticks(d3.time.days, 1)
.tickFormat(function(d) {
return d3.time.format('%d/%m/%Y')(new Date(d));
});
chart.yAxis //Chart y-axis settings
.axisLabel('Custo (R$)')
.tickFormat(d3.format('$,2'));
/* Done setting the chart up? Time to render it!*/
var myData = buildData(); //You need data...
d3.select('#chart') //Select the <svg> element you want to render the chart in.
.datum(myData) //Populate the <svg> element with chart data...
.call(chart); //Finally, render the chart!
nv.utils.windowResize(function() { chart.update() });
return chart;
});
function buildData() {
var ret = [];
for (var i = 0; i < dados.length; i++) {
var dado = dados[i];
var serie = { key : dado.descricao, values: [] };
for (var j = 0; j < dado.valores.length; j++) {
var valor = dado.valores[j];
serie.values.push({ x: new Date(valor.data), y: valor.valor });
}
ret.push(serie);
}
return ret;
}
</script>
</head>
<body>
<svg id="chart" style="height: 100%; width: 70%;"></svg>
</body>
</html>
Can someone help me to do one of the both?
I've been looking through tons of examples but I can't seem to get my code to pull out the data. The chart is blank.
I have a php file that gives the following: (date, value1, value2)
[
["2013-09-15 08:44:37",19.8,8.19],
["2013-09-15 08:47:37",18.4,7.81],
["2013-09-15 08:50:37",18.3,7.78],
["2013-09-15 08:53:37",18.1,7.77]
]
I then have the following code:
<!DOCTYPE html>
<head>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/highcharts.js" type="text/javascript"></script>
<script>
var chart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
type: 'line',
},
title: {
},
xAxis: {
type: 'datetime'
},
yAxis: {
},
series: [{
name: 'val1',
data: []
}, {
name: 'val2',
data: []
}]
};
$.getJSON('data_day.php', function(json) {
val1 = [];
val2 = [];
$.each(json, function(key,value) {
val1.push([value.time, value.val1]);
val2.push([value.time, value.val2]);
});
options.series[0].data = val1;
options.series[1].data = val2;
chart = new Highcharts.Chart(options);
});
});
</script>
</head>
<html>
I'm trying to use firebug to see where I've gone wrong. If I put
console.log(key,value)
under the $.each I can see the data:
0 ["2013-09-15 08:50:37", 18.3, 7.78]
1 ["2013-09-15 08:53:37", 18.1, 7.77]
2 ["2013-09-15 08:56:37", 18.2, 7.8]
Is there a problem with the
val1.push([value.time, value.val1]);
or
options.series[0].data = val1;
Update: Changed it to this and its now working.
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);
As per Pal's comment - changed it to this:
val1.push([value[0], value[1]]);
val2.push([value[0], value[2]]);