Store Highcharts in Javascript Function - How to? - javascript

I am trying to store the entire Highcharts/Highstocks script into a function for js to make things a bit more compact and easier to replicate.
$(function() {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container'
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : [[1,2],[4,5]],
tooltip: {
valueDecimals: 2
}
}]
});
});
This is basically whats in the file highchartsfunc.js that I call for the function. Any idea?

You already have it in a function, just one that executes immediately. Here it is in a callable form with the data and renderto defined by the caller:
function createNewChart(data, render) {
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : render
},
rangeSelector : {
selected : 1
},
title : {
text : 'AAPL Stock Price'
},
series : [{
name : 'AAPL',
data : data,
tooltip: {
valueDecimals: 2
}
}]
});
}
then you can call it like this from wherever you like:
createNewChart([[1,2],[4,5]], 'container');

Related

Highcharts | Graph with category names in the middle

I have to set up a graph for a web application, and I decided to use Highcharts because it seems to be the most flexible. I managed to create what I wanted, but I can't do it in one graphic, I have to create two.
My goal is to have a bar graph, with negative values on the left and positive values on the right, and category names in the middle (and being able to place HTML in it but it's secondary).
Here is the link to what I have today:
$(function() {
Highcharts.setOptions({
chart : {
type : 'bar'
},
title : { text : '' },
subtitle : { text : '' },
plotOptions : {
bar : { dataLabels : { enabled : true }}
},
legend : { enabled : false },
credits : { enabled : false },
yAxis : {
title : false,
opposite : true
},
xAxis : {
categories : ['Apples', 'Oranges', 'Pears', 'Grapes', 'Bananas'],
labels : { format : "" },
type : "category",
visible : false,
title : false,
showEmpty: false,
reversed : true
}
});
// Graphique gauche (négatifs)
var leftChart = new Highcharts.Chart({
chart: { renderTo: 'gphLeft' },
yAxis: { reversed : false },
xAxis: { opposite : true },
series : [{
data : [null, -150, null, null, -680]
}]
});
// Graphique droite (positifs)
var rightChart = new Highcharts.Chart({
chart: { renderTo: 'gphRight' },
yAxis: { reversed : false },
xAxis: { opposite : false },
series : [{
data : [180, null, 258, 487, null]
}]
});
});
I have tried different techniques and answers found on the Internet, but I can't find a solution.
(I hope you understand, because I use a translator)
Can somebody help me?

Reset entire series data and redraw in highcharts

I am currently working on an angular 5 application adn using highcharts for charts. I have a stacked bar chart with me. It plots the volume of positive, neutral, negative data across various categories.
The xAxis categories are
['Cat1', 'Cat2', 'Cat3', 'Cat4', 'Cat5']
and stacking normal
plotOptions: {
series: {
stacking: 'normal'
}
}
and the series data is in the format
series : [
{name : 'positive', data : [1,5,6,8,9]},
{name : 'neutral', data : [2,6,7,8,3]},
{name : 'negative', data : [3,6,4,2,8]}
]
It works great. Now, I have an array called categorySentimentData, where each object contains a company value as well as seriesData value (which is in the required format to be fed to our chart).
{company : company.companyname,
seriesData : [
{name : 'positive', data : positiveArray},
{name : 'neutral', data : neutralArray},
{name : 'negative', data : negativeArray}
]
Now I have a select tag whose options are various company names. When i select a different company, the chart should be fed with the appropriate series data and redrawn.
My chart creation code :
this.categorySentimentChart = new Highcharts.Chart('compChart',{
chart : {
type : 'bar'
},
title : {
text : this.selectedCompany
},
xAxis : {
categories : categoryList,
},
yAxis : {
title : {
text : ''
}
},
legend : {
reversed : true,
layout : 'horizontal',
align : 'center',
verticalAlign : 'bottom'
},
plotOptions: {
series: {
stacking: 'normal'
}
},
series : this.categorySentimentData.filter((com) => com.company == this.selectedCompany)[0].seriesData
});
I have searched for ways to change series data and redraw the chart. They all have the same code
chart.series[0].setData([1,2,3,4,5]);
Is there a way i can reset the entire series data and redraw it? This is function i currently use when a company is selected
onCompanyChange() {
let targetSeriesData = this.categorySentimentData.filter((com) => com.company == this.selectedCompany)[0].seriesData;
this.categorySentimentChart.series.forEach((item, index) => {
this.categorySentimentCompetitorChart.series[index].setData(targetSeriesData[index], false);
});
console.log(this.categorySentimentCompetitorChart.series);
this.categorySentimentCompetitorChart.redraw(); }
But this isn't working. The chart disappears as soon as I click a company. Please guide me on how to achieve the desired functionality. Here is a jsfiddle link recreating the scenario as close as possible https://jsfiddle.net/j8zyx6ba/19/ . TIA

How to pass highchart series to highchart title?

I've created a Pie Chart, using Highcharts. I have a title and I need to inject the name of data series inside the title. So it's like this:
title: {
text: 'Data name: {name}',
align: 'center',
useHTML: true,
verticalAlign: 'middle',
y: -70
},
series: [{
type: 'pie',
name: 'Some name to be injected inside the title',
innerSize: '70%',
data: []
}]
Is it possible to do that?
I would do this by identifying or retrieving the series name first, and assigning it to a variable to be used within the chart configuration options.
Whatever method you're using to retrieve or process the data for the series object of the chart should be able to provide you the name to use independently.
Like:
//process data...
var seriesData = [['Group A', 1598],['Group B', 872],['Group C', 321]];
var seriesName = 'Chart Series Name';
$(function() {
$('#container').highcharts({
chart : { type : 'pie' },
title : { text : seriesName },
subtitle : { text : null },
tooltip : { },
plotOptions : { },
series : [{
name : seriesName,
data : seriesData
}]
});
})
Example:
http://jsfiddle.net/jlbriggs/3d3fuhbb/64/
There is no direct way to do this. I suggest to use the load event of highcharts:
chart: {
/* some other code */
events: {
load: function () {
//collect information
var title_old = this.title.textStr,
title_new,
substitute= this.series[0].name,
needle = '{name}';
//replaceing 'needle' with 'substitute'
title_new = title_old.replace(needle,substitute);
//set title
this.setTitle({ text: title_new});
}
}
}
Hints:
works only if you have one series (see in code: series[0])
tested with Highcharts JS v4.1.8 (2015-08-20)
for information about String.prototype.replace() have a look here [1]
[1] : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Highcharts not displaying data on live site

I'm writing a stacked bar chart that is working fine on my local machine, however when it is running on a live server it doesn't plot any of the data points. I've considered that it could be the api is taking longer on the live site to get the data, or maybe highcharts is not loading fast enough, but the x-axis populates the values correctly and the library is loading locally (also happens with CDN).
I can even log the values of the chart series and see everything fine. It just doesn't display any data with a line designating 0 on the Y axis. Anyone have any idea what the issue could be?
$.getJSON( 'URL TO API', function(data){
// Sample data output
// data = [
// { 'name' : 'Items', data : [ 'item1', 'item2', 'item3'] }
// { 'name' : 'losses', data : [2, 3, 1] }
// { 'name' : 'Wins', data : [5, 2, 0] }
// ]
var chart = new Highcharts.Chart({
chart: {
type: 'bar',
renderTo: 'chart',
},
title: {
text: 'Wins and Losses'
},
xAxis: {
categories: data[0]['data']
},
yAxis: {
min: 0,
allowDecimals: false,
title: {
text: 'Total'
}
},
legend: {
reversed: true
},
plotOptions: {
series: {
stacking: 'normal',
}
},
series: [
{
name : data[1]['name'],
data : data[1]['data']
},
{
name : data[2]['name'],
data : data[2]['data']
},
]
});
});

Displaying a json file with highstock

I have some difficulties displaying a graph with Highstock. It seems like I can't have access to the x-axis part where the graph should be displayed. I am new with Highstocks so my code could seem like a mess but my idea was the following:
First access the json file from the server. Convert it in the right format [[datestamp, value], ....]. Then display the graph.
Here is my Json file (file.json):
[{"date":"2013-10-04T22:31:12.000Z","value":30000},{"date":"2013-10-04T22:31:58.000Z","value":35000},{"date":"2013-10-04T22:32:05.000Z","value":60000},{"date":"2013-10-04T22:32:12.000Z","value":45000}]
My code is the following:
$(function() {
chartOjb = new Object();
var mydata = [];
$.getJSON('file.json', function(data) {
$.each(data, function (index, item) {
chartOjb.name = getTimestamp(item.date);
chartOjb.data = item.value;
mydata.push({ x: chartOjb.name, y: parseFloat(chartOjb.data) });
});
$('#container').highcharts('StockChart', {
chart: {
type: 'candlestick',
zoomType: 'x'
},
navigator: {
adaptToUpdatedData: false,
series: {
data: mydata
}
},
scrollbar: {
liveRedraw: false
},
xAxis: {
type: 'datetime',
title: 'Time',
//minRange: 3600 * 1000/15 // one hour
},
rangeSelector : {
selected : 1
},
title : {
text : value
},
series : [{
name : 'Capacité',
data : data,
tooltip: {
valueDecimals: 2
}
}] }); });
});
Thank you very much for your help
Could you add your function getTimestamp()? Maybe there is something wrong.
Keep in mind that:
x-value should be timestamp,
when using a lot of objects { x: x, y: y }, set turboThreshold

Categories

Resources