Json in perfect form but Highcharts chart won't populate - javascript

New to highcharts and as the title said I am trying to pull json from a webservice and place it into the chart (bar chart) but I am getting some weird behavior. after I pull the data down through $http.get() I try and set the series to that string of json like series: '$scope.jsondata'. It will fill some legends (more than expected) so it is getting the data. but the bars on the chart wont show.
On the other hand when I go to the url where I am getting the json and just copy and paste all of the json into the series field, it works perfectly.
I have a plunker here I have been working on that shows what I am talking about. You can just paste:
[
{
"name":"Kaia",
"data":[19]
},
{
"name":"Deborah",
"data":[86]
},
{
"name":"Phoebe",
"data":[77]
},
{
"name":"Rory",
"data":[17]
},
{
"name":"Savannah",
"data":[15]
}
]
...into the series field and everything works.
EDIT I havent yet, but I am planning to use $interval to update the data every x seconds. Something like :
$http.get(fullUrl).success(function(data2) {
$scope.records = [];
data2.forEach(function(r) {
$scope.records.push(r);
});
});
mainInterval = $interval(function() {
$http.get(fullUrl).success(function(data2) {
$scope.records = [];
data2.forEach(function(r) {
$scope.records.push(r);
});
});
}, 5000);
So like one of the answers suggested I put the chart creation in the callback of the $http.get() but I think that'd hinder the $interval

You can move the creation of the Chart into the callback of the get call to simplify things. http://plnkr.co/edit/utQG34xOQmtbOukTK71e?p=preview
Note I also updated series: '$scope.jsondata' to series: $scope.jsondata.
$http.get('https://api.myjson.com/bins/38qm9').success(function(ret) {
$scope.jsondata = ret;
var chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Active Users'
},
xAxis: {
categories: ['user']
},
yAxis: {
min: 0,
title: {
text: 'Total Score',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'top',
x: -40,
y: 100,
floating: false,
backgroundColor: ((Highcharts.theme && Highcharts.theme.legendBackgroundColor) || '#FFFFFF'),
shadow: false
},
credits: {
enabled: false
},
series: $scope.jsondata
});
console.debug($scope.jsondata);
});

Related

ApexCharts: switch the tooltip title with the datalable

As the title says, i want to switch the tooltip header with the tootlip body text.
for me it makes no sense why the standard config is this way around...
i know i can create a custom tootlip but thats not my favorite way to do it.
the code im using currently
var options = {
series: [{
name: 'Series',
data: [v0, v1, v2, v3, v4]
}],
colors: ['#3979bd', '#c1a748', '#69b761', '#69b761', '#d54c4c'],
chart: {
type: 'bar',
height: 200
},
plotOptions: {
bar: {
distributed: true,
borderRadius: 0,
horizontal: true,
}
},
tooltip: {
enabled: true,
},
dataLabels: {
enabled: true,
},
xaxis: {
categories: ['open', 'planned', 'done', 'done cloud', 'stopped'],
}
};
var chart = new ApexCharts(document.querySelector("#overview_apex_sc4stats"), options);
chart.render();
and heres a image what i want

Highcharts second series name labeled to 'Series 2'?

Just started a week ago to learn and use Highcharts. In my application a user selects a key value from a list box and, out of that key an array of values will be retrieved and, used the data to create a multiple series of line graph. In the screenshot below the first series (in light blue color) has the name of CDEP158 and, on the second series (in black color), the series name shouldn't be 'Series 2', it should be CDT158. 'Series 2' for the second series is the issue here.
This is the chart data preparation code which accepts dataChart (result) from jquery post callback function called in a click event.
function prepareChartData(dataChart)
{
var dataSeries = [];
var xTitle;
for (var i = 0; i < dataChart.length; i++) {
var items = dataChart[i];
var xDate = +moment(items.Time);
var seriesData = parseFloat(items.Value);
dataSeries.push([xDate, seriesData]);
xTitle = items.Name;
}
if (aeChart === undefined || aeChart === null)
{
plotChartData(dataSeries, xTitle);
return;
}
aeChart.addSeries({
title: xTitle,
data: dataSeries
});
};
Function that creates a new instance of Highchart and its configuration:
function plotChartData(dataseries, xtitle)
{
aeChart = new Highcharts.Chart({
chart: {
renderTo: 'svgtrendspace',
type: 'line',
zoomType: 'xy',
panning: true,
panKey: 'shift',
plotBorderWidth: 1
},
title: {
text: ''
},
legend: {
layout: 'horizontal',
align: 'left',
itemDistance: 10,
borderWidth: 0,
itemMarginTop: 0,
itemMarginBottom: 0,
padding: 20
},
plotOptions: {
series: {
states: {
hover: {
enabled: false
}
},
dataLabels: {
enabled: false,
format: '{y}'
},
allowPointSelect: false
}
},
xAxis: {
type: 'datetime',
labels: {
rotation: -65,
style: {
fontSize: '9px',
fontFamily: 'Verdana, sans-serif'
}
}
},
yAxis: {
gridLineColor: '#DDDDDD',
gridLineWidth: 0.5
},
series: [{
name: xtitle,
data: dataseries,
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b><br/>',
valueDecimals: 2
}
}]
});
};
Why is that the first series gets the correct name but on the second one it did not? Is my highcharts configuration wrong? How should I properly configure or format it to address the issue?
I have googled it for similar issues related with multiple series but I couldn't find any similar questions or answers that would help me.
The fact that it works for the first series implies that the issue isn't with your code, but rather is with your init.
Can you put a console.log('Title: ' + xTitle); statement right before you call aeChart.addSeries() in the above function to check on what you are passing in? My suspicion is that the second series is not being passed a title, and that HighCharts is therefore putting in Series2 on its own.
Maybe you should not be setting the value of xTitle in every single iteration of the initial for loop?

How to fetch json array data into highcharts in angularjs

I want to display a bar graph using highcharts.I am devoloping an app in play framework(play-java),in which I return a response from the java api which contains data in json format.It contains a field 'name' which contains data like 'Data','Gadgets','Others' etc.I want the x axis of the chart to take these values from json array which gets returned in response.
Here is the code for the response in .js
for(var i=0;i<response.data.result.length;i++)
{
$scope.total=$scope.total+parseInt(response.data.result[i].item_price);
}
var j=0;
console.log(response.data.result);
while(j<response.data.result.length)
{
$scope.jsonArray=[{
name:response.data.result[j].category_name,
y: (parseInt(response.data.result[j].item_price)/$scope.total)*100,
}]
$scope.renderChart();
}
The code for bar graph
$scope.renderChart = function()
{
Highcharts.chart('container', {
chart: {
type: 'column'
},
title: {
text: 'Your Expenses'
},
subtitle: {
text: 'Your total spent money is '+$scope.total+'.'
},
xAxis: {
type: 'category'
},
yAxis: {
title: {
text: 'Money spent in percentage'
}
},
legend: {
enabled: false
},
credits: {
enabled: false
},
plotOptions: {
series: {
borderWidth: 0,
dataLabels: {
enabled: true,
format: '{point.y:.1f}%'
}
}
},
tooltip: {
headerFormat: '<span style="font-size:11px">{series.name}</span><br>',
pointFormat: '<span style="color:{point.color}">{point.name}</span>: <b>{point.y:.2f}%</b> of total<br/>'
},
series: [{
name: 'Categories',
colorByPoint: true,
data:$scope.jsonArray
}]
});
}
I know that I can't use the while loop in the response code mentioned.That's where i am looking help for.The y axis should calculate the percentage value .I want to generate 'names' for x axis and percentage for y axis of the chart.Thanks in advance..
All we have to do is to just initialize the jsonArray as empty before doing the looping.Add a for loop so that it iterates through the array and assigns the values appropriately.
The changed code
$scope.jsonArray = [];
for(var i=0;i<response.data.result.length;i++)
{
$scope.jsonArray[i]={
name:response.data.result[i].category_name,
y: (parseInt(response.data.result[i].item_price)/$scope.total)*100,
}
$scope.renderChart();
console.log(response.data.result[i]);
}
console.log($scope.jsonArray);
})
Anyway thanks....

javascript highcharts builder function

I am trying to make a function which will be building Highcharts charts dynamically based on parameters passed. I do it the following way:
function makeChart(name, title, series)
{
var options = {
chart: {
type: 'areaspline',
renderTo: name
},
credits: { enabled: false },
legend: { enabled: true },
title: {
text: title
},
xAxis: {
type: 'datetime'
},
yAxis: {
gridLineDashStyle: 'dot',
title: {
text: 'Quantity'
}
},
plotOptions: {
areaspline: {
animation: false,
stacking: '',
lineWidth: 1,
marker: { enabled: false }
}
},
series: [] //chart does not display except title. It will draw if I paste the data here manually
};
this.chart = new Highcharts.Chart(options);
for (index = 0; index < series.length; ++index) {
options.series[index] = {'name':series[index][0], 'data':series[index][1], 'color':series[index][2], 'fillOpacity': .3};
}
}
makeChart('container2', 'second chart', [['thisisname1', [20,21,22,23,24,25,26,27,28], '#d8d8d8']]);//calling function with test parameters
But everything I can see is the charts title. I guess the problem is in adding data to series array. I tried to add it with several ways but it did not work, although I see that the data has been added if I console.log(options.series). Any ideas how to fix that? Thank you.
Place this.chart = new Highcharts.Chart(options); after the for loop.
You're adding the data after the chart has been initialized, for it to work this way you need to tell HighCharts to redraw itself, easier option is to init after the loop. :)

Highcharts multiple y axis with data from csv file

I've been creating charts on my company's website with data that is populated from a csv file. I need to add two additional y axes on the right side of the chart. I tried doing so by following Highchart's instructions, but my data is coming from a CSV file and I can't manage to get the two additional axes to connect to the data. Meaning, the other two splines look flat compared to the one that is actually plotting to it's y axis.
Below is the chart's JS file. The CSV file is 4 columns, which from left to right are Date, Overall, VIX, GSPC
Thank you in advance!
function basi_overall_chart() {
//var to catch any issues while getting data
var jqxhr_basi_overall = $.get('../../datafiles/basi/company_BASI_Overall_VIXSP.csv', function (data) {
var options = {
//chart options
chart: {
//set type of graph, where it renders
type: 'line',
renderTo: 'basi_overall_container'
},
//set title of graph
title: {
text: 'company Bid-Ask Spread Index (BASI)',
style: {
color: '#4D759E'
},
align: 'center'
},
//set xAxis title
xAxis: {
title: {
text: 'Date',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
}
},
//set yAxis info
yAxis: [{
title: {
text: 'Basis Points (BPS)',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
},
labels: {
//give y-axis labels commas for thousands place seperator
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
//set y-axis to the left side
opposite: false,
//set background grid line width
gridLineWidth: 1
}, { // Second yAxis
gridLineWidth: 1,
title: {
text: 'VIX',
style: {
color: '#de5a3c',
fontWeight: 'bold'
}
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
opposite: true
}, { // Third yAxis
gridLineWidth: 1,
title: {
text: 'SP',
style: {
color: '#4D759E',
fontWeight: 'bold'
}
},
labels: {
formatter: function () {
return Highcharts.numberFormat(this.value);
}
},
opposite: true
}],
//stylize the tooltip
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b><br/>',
valueDecimals: 4
},
//enable and stylize the legend
legend: {
enabled: true,
layout: 'horizontal',
align: 'center',
borderWidth: 1,
borderRadius: 5,
itemDistance: 20,
reversed: false
},
//set the starting range. 0-5. 5="All", 4="1yr", etc
rangeSelector: {
selected: 5,
allButtonsEnabled: true
},
//set general plot options
plotOptions: {},
//disable credits
credits: {
enabled: false
},
//make download as csv format correctly
navigator: {
series: {
includeInCSVExport: false
}
},
//set name of chart downloads
exporting: {
filename: 'company_basi_overall',
//enable download icon
enabled: true,
//add image to download
chartOptions: {
chart: {
events: {
load: function () {
this.renderer.image('http://www.company.com/images/company_logo2.gif', 90, 75, 300, 48).attr({
opacity: 0.1
}).add();
}
}
},
//remove scrollbar and navigator from downloaded image
scrollbar: {
enabled: false
},
navigator:{
enabled: false
}
},
//make download as csv format correctly
csv: {
dateFormat: '%Y-%m-%d'
}
},
//set graph colors
colors: ['#002244', '#DBBB33', '#43C5F3', '#639741', '#357895'],
//series to be filled by data
series: []
};
//names of labels in order of series. make sure they are the same as series header in data file
var names = ['BASI', 'VIX', 'SP'];
//get csv file, multiply by 100 (divide by .01) and populate chart
readCSV(options, data, 1.0, names);
var chart = new Highcharts.StockChart(options);
})
//catch and display any errors
.fail(function (jqxhr_basi_overall, exception) {
ajaxError(jqxhr_basi_overall, exception, '#basi_overall_container');
});
}
(function () {
//set high level chart options for all charts
Highcharts.setOptions({
lang: {
thousandsSep: ','
}
});
$('.chart_container').toggle(false);
basi_overall_chart();
$('#basi_overall_container').toggle(true);
all_crossable_volume_chart();
auto_assign_toggle_chart_buttons();
})();

Categories

Resources