How to make dynamic charts in Javascript with a JSON File - javascript

So, I am new to Javascript, but I have a code to make a stable bar chart, but I need to make it dynamic.
MY JSON File format is:
"valid_columns_counts": {
"Sr no.": 0,
"Domain": 37,
"Company Name": 0,
"Address": 36,
"Industry": 38,
"Phone Number": 30,
"Zipcode": 33,
"email": 14}
I ran this code:
window.onload = function () {
var dataPoints = [];
var chart = new CanvasJS.Chart("chartContainer", {
animationEnabled: true,
title:{
},
axisY: {
title: "Percentage",
titleFontColor: "#4F81BC",
},
toolTip: {
shared: true
},
legend: {
cursor:"pointer",
itemclick: toggleDataSeries
},
data:
{
type: "column",
name: "Consistency",
legendText: "Consistency",
axisYType: "secondary",
showInLegend: true,
dataPoints: dataPoints
}
});
function addData(data) {
for (var i = 0; i < data.length; i++) {
dataPoints.push({
x: data[i].valid_columns_counts
y: data[i].valid_columns_counts
});
}
}
chart.render();
$.getJSON("localhost/sample_output.json", addData);
}
But this code shows blank page when runned.Please if someone can help me.

Related

Chart JS - Group Array Results on y axis

I think I am close to solving this but I am missing something critical. I have an array of "new" items that I am trying to plot on a chart to indicate how old they are. I can get the chart to load and plot the data but like items are not grouping onto the same line. Is there a way I can force the chart to put like types onto the same axis line in the chart? i.e. the 2 SAFE AE results load onto the same line? Any guidance would be appreciated!
var whatsNewArray = [{
"type": "EAC",
"age": -16
},
{
"type": "EAC",
"age": -58
},
{
"type": "DSCC",
"age": -36
},
{
"type": "SAFE AE",
"age": -95
},
{
"type": "SAFE AE",
"age": -94
}
]
new Chart(document.getElementById("myWHATSNEWChart"), {
type: 'scatter',
data: {
datasets: [{
data: whatsNewArray.map(function(a) {
return a.age;
}),
backgroundColor: ["#acc6ff"],
label: "New Items",
pointRadius: 10,
fill: true
}]
},
options: {
indexAxis: 'y',
maintainAspectRatio: false,
responsive: true,
layout: {
padding: 20
},
scales: {
y: {
ticks: {
color: "#a3a3a3"
},
type: "category",
labels: whatsNewArray.map(function(a) {
return a.type;
}),
grid: {
color: "#a3a3a3",
borderColor: "#a3a3a3"
}
},
x: {
title: {
display: true,
text: "MINUTES AGO",
color: "#a3a3a3"
},
ticks: {
color: "#a3a3a3"
},
beginAtZero: true,
grid: {
color: "#a3a3a3",
borderColor: "#a3a3a3"
},
border: {
color: "#a3a3a3"
}
}
},
plugins: {
legend: {
display: false,
title: {
color: "#a3a3a3"
},
labels: {
color: "#a3a3a3"
}
},
title: {
display: false,
//text: 'What is New',
color: "#a3a3a3"
}
}
}
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.dark.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
<div class="chart-container mb-4" style="position: relative;width:100%;height:250px;background-color:#283044;">
<canvas id="myWHATSNEWChart"></canvas>
</div>
I've created this minimal example, for your problem. You can add your custom options as you wish.
You have to treat the y-axis as an index, so .findIndex(el => el.type == elem.type) is checking if the elem.type exists in an array and returns the index of the found element.
var whatsNewArray = [{
"type": "EAC",
"age": -16
},
{
"type": "EAC",
"age": -58
},
{
"type": "DSCC",
"age": -36
},
{
"type": "SAFE AE",
"age": -95
},
{
"type": "SAFE AE",
"age": -94
},
{
"type": "DSCC",
"age": -2
},
{
"type": "EL",
"age": -2
},
{
"type": "PSY",
"age": -20
},
{
"type": "CNGRO",
"age": -80
},
{
"type": "CNGRO",
"age": -69
},
];
let label = [...new Map(whatsNewArray.map(item =>
[item["type"], item["type"]])).values()];
let data = whatsNewArray.map(function(elem, index) {
return {
x: elem.age,
y: label.indexOf(elem.type)
}
});
const _data = {
datasets: [{
label: 'Scatter Dataset',
data: data,
backgroundColor: 'rgb(255, 99, 132)'
}],
};
const config = {
type: 'scatter',
data: _data,
options: {
responsive: true,
layout: {
padding: 20
},
pointRadius: 10,
fill: true,
scales: {
y: {
autofill: false,
labels: label,
ticks: {
callback: function(value, index, ticks) {
return value % 1 == 0 ? label[value] : ''
}
},
}
}
}
};
new Chart(document.getElementById("myWHATSNEWChart"), config);
<link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.dark.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/6.1.0/mdb.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.2.0/chart.umd.js"></script>
<canvas id="myWHATSNEWChart"></canvas>
Explanation: So the index of an array label is being recognized as y-axis data [0,1,2....].
This returns distinct values:
[...new Map(whatsNewArray.map(item => [item["type"], item["type"]])).values()];
This checks if the value is an integer, for removing decimal values in this context.
value % 1 == 0

CanvasJS stock chart axisY doesn't update automatically with my data

I have tried the stock chart with sample data present on the CanvasJS site and it updates the Y axis everytime I scroll through it, but when I pass my data to that function it scrolls but without updating the Y-axis.
First I was trying to fetch data from array of arrays but the sample chart was using array of JSON so I converted my data to be of the exact similar manner but to no avail. I would be very thankful if you can help me on this.
My data
window.onload = function () {
CanvasJS.addColorSet("greenShades",
[//colorSet Array
"red",
"#008080",
"#2E8B57",
"#3CB371",
"#90EE90"
]);
var dataPoints = [];
var stockChart = new CanvasJS.StockChart("stockChartContainer",{
zoomEnabled: true,
theme: "light2",
colorSet: "greenShades",
exportEnabled: true, //false
title:{
text:""
},
subtitles: [{
text: ""
}],
rangeSelector: {
buttons: [
{
range: 10, //Change it to 6
rangeType: "day",
label: "10D"
},
{
range: 1, //Change it to 6
rangeType: "month",
label: "1M"
},
{
range: 6, //Change it to 6
rangeType: "month",
label: "6M"
},
{
range: 1, //Change it to 6
rangeType: "year",
label: "1Y"
},
{
rangeType: "all",
label: "All" //Change it to "All"
}
]
},
charts: [{
axisX: {
},
axisY: {
prefix: "",
suffix: "",
title: "",
viewportMinimum: 20,
viewportMaximum: 200,
titleFontSize: 14
},
data: [{
type: "area",
xValueFormatString: "MMM YYYY",
yValueFormatString: "#,###.##M",
dataPoints : dataPoints
}]
}],
navigator: {
// slider: {
// minimum: new Date(2010, 00, 01),
// maximum: new Date(2014, 00, 01)
// }
}
});
$.getJSON("https://financialmodelingprep.com/api/v3/historical-price-full/AAPL?apikey=API_KEY", function(data) {
for(var i = 0; i < data.historical.length; i++){
dataPoints.push({x: new Date(data.historical[i].date), y: Number(data.historical[i].close)});
}
console.log(dataPoints)
stockChart.render();
});
}

highcharts with json data

I am new to these things. Using the code from URL: http://jsfiddle.net/sujay/UMeGS/ , I was trying to create a chart with my own data.
Using REST web service, I am able to get my data from database, which means when I click on the following link 'localhos:48095/WebApplication22/webresources/sample22.test15' , I am getting json data as follows
[
{
"id": 1,
"status": "stopped",
"unit": "a",
"val": 24
},
{
"id": 2,
"status": "working",
"unit": "a",
"val": 59
},
{
"id": 3,
"status": "turning",
"unit": "a",
"val": 2
},
{
"id": 5,
"status": "transport",
"unit": "a",
"val": 6
},
{
"id": 6,
"status": "stopped",
"unit": "b",
"val": 336
},
{
"id": 7,
"status": "working",
"unit": "b",
"val": 212
},
{
"id": 9,
"status": "turning",
"unit": "b",
"val": 23
},
{
"id": 10,
"status": "transport",
"unit": "b",
"val": 1
}
]
I have slightly modified code from http://jsfiddle.net/sujay/UMeGS/, in which I have used getJSON() to get data.
Below is the code.
$(function () {
$.getJSON('localhos:48095/WebApplication22/webresources/sample22.test15', function (data) {
var seriesData = [];
var xCategories = [];
var i, cat;
for (i = 0; i < data.length; i++) {
cat = 'Unit ' + data[i].unit;
if (xCategories.indexOf(cat) === -1) {
xCategories[xCategories.length] = cat;
}
}
for (i = 0; i < data.length; i++) {
if (seriesData) {
var currSeries = seriesData.filter(function (seriesObject) {
return seriesObject.name == data[i].status;
});
if (currSeries.length === 0) {
seriesData[seriesData.length] = currSeries = {
name: data[i].status,
data: []
};
} else {
currSeries = currSeries[0];
}
var index = currSeries.data.length;
currSeries.data[index] = data[i].val;
} else {
seriesData[0] = {
name: data[i].status,
data: [data[i].val]
}
}
}
var chart;
$(document).ready(function () {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'column'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: xCategories
},
yAxis: {
min: 0,
title: {
text: 'Total fruit consumption'
},
stackLabels: {
enabled: true,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -100,
verticalAlign: 'top',
y: 20,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' + this.series.name + ': ' + this.y + '<br/>' +
'Total: ' + this.point.stackTotal;
}
},
plotOptions: {
column: {
stacking: 'normal'
}
},
series: seriesData
});
});
});
});
But I am unable to see anything. Chart is not displayed. Please help me on this thing.

How to get all json values in line chart

I have many Json values, using them I am going to create a line chart but it shows only one value in the chart. I am a newbie to javascript and have an idea to plot all values in chart. please anybody give jsfiddle example for this issue.
HTML code
<div id="chartContainer" class="chart">
Script
$.getJSON('dashboard_summary.php?', function(data) {
var len = data.length
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len);
});
});
function chart (dates,Tip,Rev,len) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: [
{
x: new Date(dates),
y: parseInt(Tip)
}
]
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: [
{
x: new Date(dates),
y: parseInt(Rev)
}
]
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
};
Json data
{
"Date": "2014-01-30",
"CarsParked": "1",
"RevenueWithTip": "0",
"Revenue": "0",
"Tip": "0",
},
{
"Date": "2014-01-31",
"CarsParked": "10",
"RevenueWithTip": "10",
"Revenue": "7",
"Tip": "3",
},
{
"Date": "2014-02-28",
"CarsParked": "28",
"RevenueWithTip": "55",
"Revenue": "47",
"Tip": "8",
}
Based on your code, I can see why the chart shows only one point, which is the last data point of those points expected to be shown on the chart. Here is the problem:
var len = data.length;
/* Loop through each item in the data */
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len); /* Draw a chart with one point */
});
So you end up drawing many charts with the last chart which has the last data point to replace all the previous charts.
Instead, you should adjust the foreach block as follow and draw the chart once you've converted the data into an array of points.
$.getJSON('dashboard_summary.php?', function(data) {
var Tips = [];
var Revs = [];
$.each(data, function(i, v) {
Tips.push({ x: new Date(v.Date), y: parseInt(v.Tip) });
Revs.push({ x: new Date(v.Date), y: parseInt(v.Revenue) });
});
chart(Tips, Revs);
});
Also, you can format the x-axis to make the chart look prettier (The format of the x-axis here is designed for the data given above. In your application, you may have to use another format style depending on the actual data):
function chart (Tips, Revs) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM",
interval:14,
intervalType: "day"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: Tips
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: Revs
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
A jsFiddle is made here for your review.
Updated codes. it Works >> Pastebin
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src = "http://canvasjs.com/wp-content/themes/bootstrap_child/assets/js/jquery-1.8.3.min.js"> </script>
<script type="text/javascript" src="http://canvasjs.com/assets/script/canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" class="chart">
<script type="text/javascript">
data=[
{
"Date": "2014-01-30",
"CarsParked": "1",
"RevenueWithTip": "0",
"Revenue": "0",
"Tip": "0",
},
{
"Date": "2014-01-31",
"CarsParked": "10",
"RevenueWithTip": "10",
"Revenue": "7",
"Tip": "3",
},
{
"Date": "2014-02-28",
"CarsParked": "28",
"RevenueWithTip": "55",
"Revenue": "47",
"Tip": "8",
}];
var len = data.length;
$.each(data, function(i, v) {
chart(v.Date,v.Tip,v.Revenue,len);
});
function chart (dates,Tip,Rev,len) {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Revenue",
fontSize: 15
},
axisX: {
gridColor: "Silver",
tickColor: "silver",
valueFormatString: "DD/MMM"
},
toolTip: {
shared:true
},
theme: "theme2",
axisY: {
gridColor: "Silver",
tickColor: "silver"
},
legend: {
verticalAlign: "center",
horizontalAlign: "right"
},
data: [
{
type: "line",
showInLegend: true,
lineThickness: 2,
name: "Tip",
markerType: "square",
color: "#F08080",
dataPoints: [
{
x: new Date(dates),
y: parseInt(Tip)
}
]
},
{
type: "line",
showInLegend: true,
name: "Revenue",
color: "#20B2AA",
lineThickness: 2,
dataPoints: [
{
x: new Date(dates),
y: parseInt(Rev)
}
]
}
],
legend: {
cursor: "pointer",
itemclick: function(e) {
if (typeof(e.dataSeries.visible) === "undefined" || e.dataSeries.visible) {
e.dataSeries.visible = false;
} else {
e.dataSeries.visible = true;
}
chart.render();
}
}
});
chart.render();
}
</script>
</body>
</html>
jsFiddle
Update Code:
dataRevenue=
[
{ x: new Date(2014, 00,30), y: 0 },
{ x: new Date(2014, 01,31), y: 7},
{ x: new Date(2014, 02,28), y: 47}
];
dataTip =[
{ x: new Date(2014, 00,30), y: 0 },
{ x: new Date(2014, 01,31), y: 3},
{ x: new Date(2014, 02,28), y: 8}
];
var chart = new CanvasJS.Chart("chartContainer",
{
theme: "theme2",
title:{
text: "line chart"
},
axisX: {
valueFormatString: "MMM",
interval:1,
intervalType: "month"
},
axisY:{
includeZero: false
},
data: [
{
type: "line",
//lineThickness: 3,
dataPoints: dataTip
},
{
type: "line",
//lineThickness: 3,
dataPoints: dataRevenue
}
]
});
chart.render();

Populate Jqplot from remote JSON

I'm trying to populate a bar chart from an external JSON in a PHP file. I've trying to use AJAX and getJSON function to do this but still failed to generate a chart.
Here is how my JSON format look like:
[
{
"NAME": "a chart",
"VALUES": "[[439, 233, 233, 495],[292, 360, 262, 173],[222, 95, 27, 27]]"
}
]
Here is the javascript:
$(document).ready(function() {
urlDataJSON = 'data.php';
$.getJSON(urlDataJSON, function (data) {
console.log(data.output);
var dataLabels = ['base', 'key', 'pacing', 'emerging'];
var dataLines = json[0].VALUES;
var chartTitle = json[0].NAME;
$.jqplot('chart2', dataLines, {
legend: {
show: true
},
title: chartTitle,
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
pointLabels: {
show: true,
location: 'e',
edgeTolerance: -15
},
shadowAngle: 135,
renderOptions: {
barDirection: 'horizontal'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: dataLabels
}
}
});
});
Do you guys know what's wrong with my code above? If anything please let me know.
EDIT: Updated code
var urlDataJSON = 'data.php';
/* var json = [{
"Name": "Poll Results",
"Serie": [[2, 5, 4], [4, 1, 7], [6, 3, 1], [3, 4, 2]]}];*/
$.getJSON(urlDataJSON, function (data) {
console.log(data);
var tick = ['asd','fsdf','asda','fdsf',];
var dataLines = [];
var title = [];
$.each(data, function (entryindex, entry) {
dataLines.push(entry['VALUES']);
title.push(entry['NAME']);
});
var options = {
legend: {
show: true
},
title: 'Poll Results',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
pointLabels: {
show: true,
location: 'e',
edgeTolerance: -15
},
shadowAngle: 135,
renderOptions: {
barDirection: 'horizontal'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: tick
}
}
};
var plot = $.jqplot('chart2', [dataLines], options);
});
I've put .each() function to push data into an array. Now, the graph is empty. Only the background is showing.
$(document).ready(function() {
$.getJSON('data.php', function (data) {
var tick = ['asd','fsdf','asda','fdsf'];
var options = {
legend: {
show: true
},
title: 'Poll Results',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
pointLabels: {
show: true,
location: 'e',
edgeTolerance: -15
},
shadowAngle: 135,
renderOptions: {
barDirection: 'horizontal'
}
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: tick
}
}
};
var plot = $.jqplot('chart2', data[0].VALUES, options);
});
});
Make sure to include these plugins
<script type="text/javascript" src="../src/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="../src/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="../src/plugins/jqplot.pointLabels.min.js"></script>
This is my data.php
$arr = [
"NAME" => "a chart",
"VALUES" => [[439, 233, 233, 495],[292, 360, 262, 173],[222, 95, 27, 27]]
];
header('Content-Type: application/json');
print json_encode([$arr]);

Categories

Resources