trying to output the json value in Highcharts - javascript

Using value, value_classification, and timestamp values in json data
I am trying to print as a solid gauge of Highcharts.
The values in series data are inserted as blank values.
What's the problem?
{
"name": "Fear and Greed Index",
"data": [
{
"value": "27",
"value_classification": "Fear",
"timestamp": "21-12-2021",
"time_until_update": "-1639979045"
}
],
"metadata": {
"error": null
}
}
Using that value,
I am trying to complete the solid gauge of Highcharts.
Highcharts Demos › Solid gauge
https://www.highcharts.com/demo/gauge-solid
The code I've tried so far is below.
HTML
<div id="container-speed" class="chart-container"></div>
JAVASCRIPT
$(function () {
var processedData = [];
$.getJSON("https://api.alternative.me/fng/?date_format=en", function (json) {
for (i = 1; i > json.length; i++){
processedData.push(json[i].value);
}
var gaugeOptions = {
chart: {
type: 'solidgauge'
},
title: null,
pane: {
center: ['50%', '85%'],
size: '140%',
startAngle: -90,
endAngle: 90,
background: {
backgroundColor:
Highcharts.defaultOptions.legend.backgroundColor || '#EEE',
innerRadius: '60%',
outerRadius: '100%',
shape: 'arc'
}
},
exporting: {
enabled: false
},
tooltip: {
enabled: false
},
// the value axis
yAxis: {
stops: [
[0.1, '#55BF3B'], // green
[0.5, '#DDDF0D'], // yellow
[0.9, '#DF5353'] // red
],
lineWidth: 0,
tickWidth: 0,
minorTickInterval: null,
tickAmount: 2,
title: {
y: -70
},
labels: {
y: 16
}
},
plotOptions: {
solidgauge: {
dataLabels: {
y: 5,
borderWidth: 0,
useHTML: true
}
}
}
};
// The speed gauge
var chartSpeed = Highcharts.chart('container-speed', Highcharts.merge(gaugeOptions, {
yAxis: {
min: 0,
max: 200,
title: {
text: 'test'
}
},
credits: {
enabled: false
},
series: [{
name: 'test',
data: processedData,
dataLabels: {
format:
'<div style="text-align:center">' +
'<span style="font-size:25px">{y}</span><br/>' +
'<span style="font-size:12px;opacity:0.4">km/h</span>' +
'</div>'
}
}]
}));
});
});

Hint: Check if processedData outputs something.
Mistake: Looping over json data is incorrect as the response is an object and not an array.
Create an IIFE and verify the first part then move ahead with chart creation.
eg.
$(function () {
var processedData = [];
$.getJSON("https://api.alternative.me/fng/?date_format=en", function (json) {
// wrong
for (i = 1; i > json.length; i++){
processedData.push(json[i].value);
}
});
console.log(processedData);
});

I reproduce your code and receive the data using this approach:
fetch("https://api.alternative.me/fng/?date_format=en")
.then(response => response.json())
.then(output => {
const chartData = output.data.map(d => parseFloat(d.value))
Demo: https://jsfiddle.net/BlackLabel/s1fczwj0/

Related

How to create apexcharts (javascript) using json local file?

As the title say, I want to create apexchart using json data that I downloaded beforehand
I already search in internet to get json data use :
const df= require('data/processed.json');
And I already tried to call it df['liked'] as y and df['name'] as x
Is there something I miss?
Or call the column is not gonna do it?
I have also tried df.liked and df.name, btw
const df= require('data/processed.json');
var options = {
chart: {
height: 230,
type: 'line',
toolbar: {
show: false,
},
},
dataLabels: {
enabled: false
},
stroke: {
width: 2,
curve: 'smooth'
},
series: {
name: 'Liked',
data: df['liked']
},
legend: {
position: 'top',
},
xaxis: {
type: 'string',
data: df['name'],
axisBorder: {
show: false,
},
label: {
style: {
color: '#ccc'
}
},
},
yaxis: {
show: true,
// min: 10,
// max: 70,
labels: {
style: {
color: '#ccc'
}
}
},
colors: ['#73b4ff', '#59e0c5'],
fill: {
type: 'gradient',
gradient: {
shade: 'light',
gradientToColors: ['#4099ff', '#2ed8b6'],
shadeIntensity: 0.5,
type: 'horizontal',
opacityFrom: 1,
opacityTo: 1,
stops: [0, 100]
},
},
markers: {
size: 5,
colors: ['#4099ff', '#2ed8b6'],
opacity: 0.9,
strokeWidth: 2,
hover: {
size: 7,
}
},
grid: {
borderColor: '#cccccc3b',
}
}
var chart = new ApexCharts(document.querySelector("#unique-visitor-chart"), options);
chart.render();
enter code here
try to use :
const df = fetch("./data/processed.json")
.then(response => {
return response.json();
})
A documentation about fetch
This way will catch all data on your json and pu it in your const df by using the return :)
If you want to use require() look about : https://requirejs.org/
NOTE : Try to use a lot console.log() to debug your js app.

Loop Using Javascript in chart / Echart

i have this object and i need to convert to pie chart (i'am using echart apache)
var data = [
{
"Key": "Test1",
"value": 2
},
{
"Key": "Test2",
"value": 1
}
]
and this my script to create a chart with real data but always show me the first value from data object (Test1 , 2) i don't now the problem :)
var chartDom = document.getElementById('chart');
var myChart = echarts.init(chartDom);
var option;
//console.log(UserSourceData);
jQuery.each(UserSourceData, function (i, val) {
option = {
title: {
text: '某站点用户访问来源',
subtext: '纯属虚构',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left',
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['30%', '60%'],
data: [
{ value: val['value'] , name: val['Key'] }
],
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
});
option && myChart.setOption(option);
}
I don't know what UserSourceData represents but if you want the datapoints from the data object,you need to run the loop only for the data property within the options object.A map function would do the trick.
var chartDom = document.getElementById('chart');
var myChart = echarts.init(chartDom);
const option = {
title: {
text: '某站点用户访问来源',
subtext: '纯属虚构',
left: 'center'
},
tooltip: {
trigger: 'item'
},
legend: {
orient: 'vertical',
left: 'left',
},
series: [
{
name: '访问来源',
type: 'pie',
radius: ['30%', '60%'],
data: data.map(obj => ({value:obj['value'],name:obj['Key']})),
emphasis: {
itemStyle: {
shadowBlur: 10,
shadowOffsetX: 0,
shadowColor: 'rgba(0, 0, 0, 0.5)'
}
}
}
]
};
option && myChart.setOption(option)

Highcharts: Add point without connecting series

All,
I'm trying to allow for a user to click on a highchart between two data points and draw a line. The resulting line will calculate LARGESTVALUE-SMALLESTVALUE above the rendered line.
I'm attempting to use this example (http://jsfiddle.net/2MdEN/1/).
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'scatter',
margin: [70, 50, 60, 80],
events: {
click: function(e) {
// find the clicked values and the series
var x = e.xAxis[0].value,
y = e.yAxis[0].value,
series = this.series[0];
// Add it
series.addPoint([x, y]);
}
}
},
title: {
text: 'User supplied data'
},
subtitle: {
text: 'Click the plot area to add a point. Click a point to remove it.'
},
xAxis: {
minPadding: 0.2,
maxPadding: 0.2,
maxZoom: 60
},
yAxis: {
title: {
text: 'Value'
},
minPadding: 0.2,
maxPadding: 0.2,
maxZoom: 60,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
series: {
lineWidth: 1,
point: {
events: {
'click': function() {
if (this.series.data.length > 1) this.remove();
}
}
}
}
},
series: [{
data: [[20, 20], [80, 80], null, [60, 40], [85, 60]]
}]
});
});
});
The problem is that is connects the last data point in the series to the newly added point. I'd like the points to be detached from the series to allow for lines being drawn above the generated chart.
Is there any way to accomplish this?
Thank you
You can include a second empty series in your chart config, and change which series you are adding a point to:
events: {
click: function(e) {
// find the clicked values and the series
var x = e.xAxis[0].value,
y = e.yAxis[0].value,
series = this.series[1]; <------------
// Add it
series.addPoint([x, y]);
}
}
You can also then move your point click event into the second series, if you don't want users to be able to remove points from the original data:
series: [{
data: [
[20, 20],
[80, 80], null, [60, 40],
[85, 60]
]
}, {
id: 'dummy',
color: 'rgba(204,0,0,0.9)',
point: {
events: {
'click': function() {
this.remove();
}
}
}
}]
Updated example:
http://jsfiddle.net/2MdEN/107/
I used the following
$(function () {
$('#container').highcharts({
chart: {
type: 'scatter',
margin: [70, 50, 60, 80],
events: {
click: function (e) {
var c = this.series[0].chart;
var s = this.series.length;
var x = e.xAxis[0].value;
var y = e.yAxis[0].value;
if(s == 1) {
c.addSeries('newSeries' + new Date());
c.series[1].addPoint([x, y]);
}else{
if(this.series[this.series.length-1].data.length%2 == 1) {
c.series[this.series.length-1].addPoint([x, y]);
}else{
c.addSeries('newSeries' + new Date());
c.series[this.series.length-1].addPoint([x, y]);
}
}
}
}
},
title: {
text: 'User supplied data!!!!'
},
subtitle: {
text: 'Click the plot area to add a point. Click a point to remove it.'
},
xAxis: {
gridLineWidth: 1,
minPadding: 0.2,
maxPadding: 0.2,
maxZoom: 60
},
yAxis: {
title: {
text: 'Value'
},
minPadding: 0.2,
maxPadding: 0.2,
maxZoom: 60,
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
legend: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
series: {
lineWidth: 1,
point: {
events: {
'click': function () {
if (this.series.data.length > 1) {
this.remove();
}
}
}
}
}
},
series: [{
data: [[20, 20], [80, 80]]
}]
});
});

how to map serial and data points using json Array

I am creating multi serial line chart using highchart.
My Json (cleanData) look like this...
[{
"key": "port_A",
"value": [
[1447596900000, 0],
[1447596960000, 0],
[1447597020000, 1]
]
}, {
"key": "port_B",
"value": [
[1447596900000, 0],
[1447596960000, 4]
]
} {
"key": "port_C",
"value": [
[1447596900000, 0],
[1447596960000, 0],
[1447597020000, 1]
}]
How can I map "key" as serial and "value" as data points on highchart
$(document).ready(function () {
Highcharts.setOptions({
colors: ['#058DC7', '#50B432', '#ED561B', '#DDDF00', '#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'pie',
zoomType: 'y',
resetZoomButton: {
position: {
// align: 'right', // by default
// verticalAlign: 'top', // by default
x: 0,
y: -30
}
},
options3d: {
enabled: true,
alpha: 15,
beta: 15,
depth: 50
}
},
title: {
text: 'Users by region',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
type: 'category',
//categories: ['APAC', 'test2', 'test3', 'test4'],
labels: {
rotation: -45,
style: {
'fontSize': '10px',
'fontFamily': 'Verdana, sans-serif',
'color': '#333',
'text-transform': 'uppercase',
'font-weight': '600'
}
}
},
yAxis: {
min: 0,
title: {
text: 'Number of users '
}
},
legend: {
enabled: false
},
tooltip: {
pointFormat: '#users: <b>{point.y:.1f}</b>'
},
credits: {
enabled: false
},
exporting: {
enabled: false
},
plotOptions: {
column: {
depth: 25
}
},
series: []
});
var cleanData1 = JSON.stringify(myArray);
var cleanData = $.parseJSON(cleanData1);
console.log(JSON.stringify(cleanData));
chart.series = cleanData;
});
You need to iterate over your json and put the name and data in an object as like below
var seriesData = [];
$.each(clearData, function(i,item){
seriesData.push({name:clearData[i].key,data:clearData[i].value});
console.log("seriesData"+JSON.stringify(seriesData));
});
See working fiddle here

HighCharts - Creating a Scatter with datetime

I want to create a scater with datetime as the xAxis, I managed to do so but the x-interval is with days, I am having a hard time doing so where the x-interval is with minutes.
My JS:
function startDashboard3DScatter() {
$.getJSON('/Handlers/MainHandler.ashx?op=getNetwork', function (data) {
Highcharts.getOptions().colors = $.map(Highcharts.getOptions().colors, function (color) {
return {
radialGradient: {
cx: 0.4,
cy: 0.3,
r: 0.5
},
stops: [
[0, color],
[1, Highcharts.Color(color).brighten(-0.2).get('rgb')]
]
};
});
// Set up the chart
var chart = new Highcharts.Chart({
chart: {
renderTo: 'networkAlerts',
margin: 100,
type: 'scatter',
width: 600,
height: 300,
options3d: {
enabled: true,
alpha: 10,
beta: 30,
depth: 250,
viewDistance: 5,
frame: {
bottom: { size: 1, color: 'rgba(0,0,0,0.02)' },
back: { size: 1, color: 'rgba(0,0,0,0.04)' },
side: { size: 1, color: 'rgba(0,0,0,0.06)' }
}
}
},
title: {
text: 'Network'
},
plotOptions: {
scatter: {
width: 100,
height: 100,
depth: 20
},
series: {
marker: {
lineWidth: 1
}
}
},
yAxis: {
min: 0,
title: { text: 'Risk Score' }
},
xAxis: {
min: 0,
max: 6,
gridLineWidth: 1,
title: { text: 'Time line' },
labels: {
formatter: function () {
var date = new Date();
date.setDate(date.getDate() - this.value);
return date.toDateFormat();// this.value + ' %';
}
}
},
zAxis: {
min: 0,
max: 10
},
legend: {
enabled: false
},
series: data
});
});
};
My data response from the get request =
data =
[
{"name":"name1", "id":"D/1", "color": "#55BF3B", "data": [[6, 100]]},
{"name":"name2", "id":"D/5", "color": "#55BF3B", "data": [[3, 1]]}
]
The data is ['days before today, yValue']
So i have done this where i send the days before today and i format xAxis, the problem as i said is that the points are with 1day interval and i want to make it 1 minute or 1 hour interval.
Any ideas, I am stuck on this for days.
Ok the solution wasn't very hard after all:
Changed:
labels: {
formatter: function () {
var date = new Date(new Date().getTime() - (this.value * 60 * 60 * 1000));
return date.toDateFormat();
}
}
And in the Server code return the hours instead of days and it works.

Categories

Resources