Highcharts not displaying chart but no errors - javascript

I'm working on data visualization with Highcharts but since I started fetching my data from an API, it doesn't display anymore.
Data is response from the API. The information is gotten from the array (trying to mimic an API here), but this still doesn't display after a lot of tweaking and it doesn't display any errors.
It be helpful if one could also point out how to display highchart errors.
$(document).ready(function() {
Highcharts.setOptions({
lang: {
numericSymbols: null
}
});
data = [{
"chart": {
"height": 500,
"renderTo": "chart_ID",
"type": "line"
},
"plotOptions": {
"line": {
"dataLabels": {
"enabled": true
},
"enableMouseTracking": false
}
},
"series": [{
"data": [5000.0, 4100.0, 1000.0, 7500.0, 5100.0, 5000.0],
"name": "Amount"
}, {
"data": [179, 86, 150, 393, 188, 322],
"name": "Millage"
}],
"title": {
"text": "Jhpiego Fuel Consumption"
},
"xAxis": {
"categories": ["3 Jul", "12 Jul", "13 Jul", "14 Jul", "15 Jul", "16 Jul"]
},
"yAxis": {
"max": 1000000,
"title": {
"text": "Fuel Price"
}
}
}]
apiData = data[0];
highChartInfo = {
chart: {
renderTo: apiData.chart.renderTo,
type: apiData.chart.type,
height: 500,
displayErrors: true
},
plotOptions: {
line: {
dataLabels: {
enabled: apiData.plotOptions.line.dataLabels.enabled
},
enableMouseTracking: apiData.plotOptions.line.enableMouseTracking
}
},
title: {
text: apiData.title.text
},
xAxis: {
categories: apiData.xAxis.categories
},
yAxis: {
title: {
text: apiData.yAxis.title.text
},
max: apiData.yAxis.max
},
series: [{
name: apiData.series[0].name,
data: apiData.series[0].data
},
{
name: apiData.series[1].name,
data: apiData.series[1].data
}
],
}
console.log(highChartInfo)
$(data[0].chart.renderTo).highcharts(highChartInfo);
});
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<div id="chart_ID" class="chart" style="height: 100%; width: 100%"></div>

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

How to make dynamic charts in Javascript with a JSON File

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.

Using custom dataformat in chart.js for Multi Axis Line Chart

The data I get from the server as a response is formatted as following:
[
{
"date": "2019-03-04T14:59:35.000Z",
"data1": 21.739999771118164,
"data2": 57.72999954223633
},
{
"date": "2019-03-04T14:59:42.000Z",
"data1": 21.739999771118164,
"data2": 57.72999954223633
},
{
"date": "2019-03-04T14:59:50.000Z",
"data1": 21.729999542236328,
"data2": 57.7400016784668
}
]
How can I use this dataformat to create a Multi Axis Line Chart with chart.js?
Using example Line Chart - Multi Axis you can try to change it a little bit and find simething like below:
var json = [
{
"date": "2019-03-04T14:59:35.000Z",
"data1": 21.739999771118164,
"data2": 57.72999954223633
},
{
"date": "2019-03-04T14:59:42.000Z",
"data1": 21.739999771118164,
"data2": 57.72999954223633
},
{
"date": "2019-03-04T14:59:50.000Z",
"data1": 21.729999542236328,
"data2": 57.7400016784668
}];
var labels = json.map(i => i.date);
var dataset1 = json.map(i => i.data1);
var dataset2 = json.map(i => i.data2);
let renderChart = function () {
var ctx = document.getElementById('canvas').getContext('2d');
new Chart(ctx, {
"type": "line",
"data": {
"labels": labels,
"datasets": [
{
"label": "Dataset1",
"data": dataset1,
"fill": false,
"borderColor": "rgb(75, 192, 192)",
"lineTension": 0.1,
yAxisID: "y-axis-1",
}, {
"label": "Dataset2",
"data": dataset2,
"fill": false,
"borderColor": "rgb(0, 192, 255)",
"lineTension": 0.2,
yAxisID: "y-axis-2",
}]
},
"options": {
responsive: false,
hoverMode: 'index',
stacked: false,
title: {
display: true,
text: 'Multi Axis'
},
scales: {
yAxes: [{
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "left",
id: "y-axis-1",
}, {
type: "linear", // only linear but allow scale type registration. This allows extensions to exist solely for log scale for instance
display: true,
position: "right",
id: "y-axis-2",
// grid line settings
gridLines: {
drawOnChartArea: false, // only want the grid lines for one axis to show up
},
}],
}
}
});
}
Above code prints:

highcharts: use JSON in drilldown

I'm new to the forum and hope to get help to complete my chart!
My problem is to call a json file in the drilldown; this is the result I would get by calling the json (for example)
http://jsfiddle.net/1dmaduwg/2/ and this is the html code and json code that I wrote to call the first json file.
HTML
<!DOCTYPE html>
<html>
<head>
<title>CHART_1</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>
<script type="text/javascript" src="http://code.highcharts.com/modules/drilldown.js"></script>
</head>
<body>
<h1 style="background: center; text-align: center; color: #E52B50"> ----------> TEST HIGHTCHARTS <----------</h1>
<div id="container" style="width: auto; height: 400px; max-width: 1000px; margin: auto">
<script type="text/javascript">
$(function () {
Highcharts.setOptions({
colors: ['#C80815', '#404040']
});
$(document).ready(function() {
var options = {
chart: {
renderTo: 'container',
backgroundColor: '#EFEFEF',
borderColor: '#FF0000',
borderWidth: 2,
borderRadius: 10,
inverted: false,
type: 'column'
},
title: {
text: 'ACTIVITIES MANAGEMENT ',
x: -20
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Activity'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
enabled: true
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'},
}
},
series: [],
}
$.getJSON("test_1.json", function(json) {
options.xAxis.categories = json[0]['data'];
options.series[0] = json[2];
options.series[1] = json[3];
chart = new Highcharts.Chart(options);
});
});
});
</script>
</div>
</body>
</html>
test_1.json
[
{
"name": "user_name",
"data": ["user_1", "user_2", "user_3", "user_4"]
},
{
"name": "user_id",
"data": ["052193002", "052193007", "052193013", "052193004"]
},
{
"name": "MANAGED",
"data": [52, 13, 42, 10]
},
{
"name": "TO MANAGE",
"data": [12, 3, 32, 1]
}
]
when I click on a column or user name I want the right data for each user in a drilldown series.
is the right way to go or I have to make changes to json (test_2) to separate the data?
can anyone help me to write the exact code to insert test_2.json into the Drilldown?
test_2.json
//USER_1
[
{
"name": "activity_name",
"data": [ "Activity 1", "Activity 2", "Activity 3"]
},
{
"name": "MANAGED",
"data": [13, 12, 27]
},
{
"name": "TO MANAGE",
"data": [3, 4, 5]
}
],
//USER_2
[
{
"name": "activity_name",
"data": [ "Activity 1", "Activity 2", "Activity 3"]
},
{
"name": "MANAGED",
"data": [3, 7, 3]
},
{
"name": "TO MANAGE",
"data": [1, 0, 2]
}
],
//USER_3
[
{
"name": "activity_name",
"data": [ "Activity 1", "Activity 2", "Activity 3"]
},
{
"name": "MANAGED",
"data": [13, 17, 12]
},
{
"name": "TO MANAGE",
"data": [13, 7, 12]
}
],
//USER_4
[
{
"name": "activity_name",
"data": [ "Activity 1", "Activity 2", "Activity 3"]
},
{
"name": "MANAGED",
"data": [5, 3, 2]
},
{
"name": "TO MANAGE",
"data": [0, 0, 1]
}
]
thank you all!!
I would vote for separate files.
It would be optimal (better performance for the chart and lower bandwidth for the connection) to do not force user to download not needed data.

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();

Categories

Resources