Adding a line of words towards the bottom of chart - highcharts

I would like to add a line of words "Country: Singapore Reporting Date: d/MMM/yy User: xxxxx " towards the bottom of chart. How should I proceed? Currently, I have my codes as below.
<script type="text/javascript">
function renderChart(divId, chartType, chartTitle, chartData, categories) {
var data = jQuery.parseJSON(chartData);
var cat = jQuery.parseJSON(categories);
console.log(cat);
console.log(chartData);
var options = createOption(divId, chartType, chartTitle, cat);
options.series = [{
allowPointSelect : true,
data : data,
showInLegend : true
}];
var chart = new Highcharts.Chart(options);
}
function createOption(divId, chartType, chartTitle, categories) {
var options = {
colors : [ '#058DC7', '#50B432', '#ED561B', '#DDDF00',
'#24CBE5', '#64E572', '#FF9655', '#FFF263', '#6AF9C4' ],
chart : {
renderTo : divId,
type : chartType
},
title : {
text : chartTitle
},
xAxis : {
categories : categories,
showEmpty: false
},
yAxis: {
showEmpty: false
},
series : []
};
return options;
}

You can use labels or renderer, which allow to add custom text / object on the chart.

Related

How to display grouped bar chart using chart.js?

I am currently building a grouped bar chart, with two different datasets using chart.js. The code in the component.js file is as follows:
createChart(){
var lbls = ['Selling', 'Cost', 'Gross'];
var curYearData = [2345, 1234, 1111];
var preYearData = [3456, 2345, 1111];
var ctx = document.getElementById(‘barChart') as HTMLCanvasElement;
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbls,
datasets: [
{
label: ‘2020',
data: curYearData,
backgroundColor: 'blue',
},
{
label: ‘2019',
data: preYearData,
backgroundColor: 'red',
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
However, I see no data displayed and instead I get an empty screen. How to create a grouped bar chart in chart.js?
There are two problems in your code.
First you don't correctly retrieve the 2D-Context.
var ctx = document.getElementById('barChart').getContext('2d');
Further you have some strange apostrophes that need to be changed.
Please have a look at your amended code below.
var lbls = ['Selling', 'Cost', 'Gross'];
var curYearData = [2345, 1234, 1111];
var preYearData = [3456, 2345, 1111];
var ctx = document.getElementById('barChart').getContext('2d');
var barChart = new Chart(ctx, {
type: 'bar',
data: {
labels: lbls,
datasets: [{
label: '2020',
data: curYearData,
backgroundColor: 'blue',
},
{
label: '2019',
data: preYearData,
backgroundColor: 'red',
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="barChart"></canvas>

Highcharts more than one series

I have a simple json document :
[ {
"x" : "a",
"y" : 2
}, {
"x" : "b",
"y" : 8
}, {
"x" : "c",
"y" : 4
}, {
"x" : "d",
"y" : 15
} ]
I want to visualize it using Highcharts having 4 series. I could success, however, the data appeared only as one series (see the next Figure).
Here is part of the code:
var options = {
.
.
.
series: [{ }]
};
.
.
.
var data = JSON.parse(json);
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
also updating the series
chart.series[0].update({
type: type,
});
works fine.
using
options.series.push({name: data[i].x, data: [data[i].x, data[i].y]});
creates 4 series but not appropriately visualized and also updating the series
chart.series[0].update({
type: type,
});
doesn't work, therefore, I want to focus in the first mentioned method.
any hints?
EDit: code which partially works for me:
var options = {
chart: {
renderTo: 'container',
type: 'column' //default
},
title: {
text: ''
},
yAxis: {
title: {
enabled: true,
text: 'Count',
style: {
fontWeight: 'normal'
}
}
},
xAxis: {
title: {
enabled: true,
text: '',
style: {
fontWeight: 'normal'
}
},
categories: [],
crosshair: true
} ,
plotOptions: {
pie: {
innerSize: 125,
depth: 80
},
column: {
pointPadding: 0.2,
borderWidth: 0,
grouping: false
}
},
series: [{ }]
};
// Set type
$.each(['column', 'pie'], function (i, type) {
$('#' + type).click(function () {
chart.series[0].update({
type: type
});
});
var data = get the data fom json file**
var seriesData = [];
for (var i = 0; i < data.length; i++) {
seriesData.push([data[i].x, data[i].y]);
options.xAxis.categories.push( data[i].x );
}
options.series[0].data = seriesData;
var chart = new Highcharts.Chart(options);
});
});
You have to decide whether you want to have 4 different series and update all 4 series at once or you want to have one series an then build e.g. legend on your own.
If you want to have 4 series, set grouping to false, set xAxis categories and each point should be mapped to one series with one point - the point.x should have the index of the series.
const series = data.map((point, x) => ({ name: point.x, data: [{ x, y: point.y }]}))
const chart = Highcharts.chart('container', {
chart: {
type: 'column'
},
plotOptions: {
column: {
grouping: false
}
},
xAxis: {
categories: data.map(point => point.x)
},
series: series
});
Then you can update your all 4 series:
chart.series.forEach(series => series.update({
type: series.type === 'column' ? 'scatter' : 'column'
}, false))
chart.redraw()
example: http://jsfiddle.net/pdjqrj5y/

Memory leak problems for column chart

I am not good at speaking English. Please understand.
I'm having a memory leak problem when using the stack column chart.
We update the data using setCategories, setData on a stack column chart every 2 seconds.
But, the memory usage continues to increase and the browser will be forcibly terminated.
The only thing that program does is call setCategories, setData. Is there anything I need to do to clean up the memory?
The test environment is os: windows7, windows10, browser: lastest version chrome 57.0.2987.133
you can see that you keep increasing after 1, 3, 5, 7, 10, 15, and 20 minutes.
Memory usage increases with time, so you can check it immediately.
You can check memory usage in the task window by running [shift + esc] shortcut in Chrome.
Send the sample code as an attachment. Thank you.
JQuery and Highcharts(5.0.10) use the latest version.
<script>
var dy = {
instanceAlias : {}
};
var CATEGORIES = ["a1","a2","a3","a4","a5","a6","a7","a8","a9","a10","a11","a12","a13","a14","a15","a16","a17","a18","a19","a20"];
var THEME = "";
var HEIGHT = "290";
var highchartConfig = {
column : {
chart: {
renderTo: null,
type: 'column'
},
xAxis: {
gridLineWidth: 1,
tickLength: 4,
categories : null,
labels : {
rotation: 0,
formatter : function(d){
return dy.instanceAlias[this.value] || this.value;
}
}
},
yAxis: {
min : 0,
max : 5,
lineWidth: 1,
tickLength: 4, // Same value as offset
tickPosition: "outside",
tickWidth: 1,
tickAmount: 3,
tickInterval : 25,
title: {
style : {
display: 'none'
}
},
stackLabels: {
style : {
"fontWeight": "normal",
color : (THEME == "dark") ? "#b0b0b3" : "#000"
}
}
},
plotOptions: {
series: {
borderRadius: 6,
borderWidth: 0,
marker :{
enabled :true,
symbol : "circle",
radius : 4
}
}
},
series: null
}
};
var stack1Config = $.extend(true,{},highchartConfig.column,{
colors : ["#009651","#ff9800","#ff1100","#009651"], //stack colors
chart: {
animation: false,
renderTo: "stack1",
height : HEIGHT
},
xAxis: {
categories : CATEGORIES
},
title: {
style: {
display: 'none'
}
},
subtitle: {
style: {
display: 'none'
}
},
legend : false,
tooltip : false,
yAxis: {
max : null,
tickInterval : null,
tickLength : null,
stackLabels: {
enabled: true,
useHTML : false,
style : {
"fontWeight": "normal",
color : (THEME == "dark") ? "#b0b0b3" : "#000"
}
}
},
plotOptions: {
column: {
stacking: 'normal',
},
series: {
animation: false,
stickyTracking: false,
enableMouseTracking: false,
lineWidth: 0,
marker: {
enabled : true,
symbol : "circle",
radius : 4
},
}
},
series : (function(){
var series = new Array();
var stack = [
{id : "normal", alias : "normal"},
{id : "warning", alias : "warning"},
{id : "danger", alias : "danger"}
];
for (var i = 0; i < stack.length; i++) {
//stack column 브러시 추가.
series.push({
name : stack[i].alias || stack[i].id,
id : stack[i].id,
lineWidth: 1,
data : (function(categories){
var data = [];
for (var i = 0; i < categories.length; i++) {
data.push(0);
}
return data;
})(CATEGORIES)
});
}
//circle
series.push({
type : "scatter",
name : "scatter",
id : "scatter",
marker: {
fillColor: '#FFFFFF',
lineWidth: 1,
lineColor: null
},
data : (function(b){
var data = [];
for (var i = 0; i < b.length; i++) {
data.push(0);
}
return data;
})(CATEGORIES)
});
console.log(series)
return series;
})()
});
var stack2Config = $.extend(true,{},highchartConfig.column,{
colors :["#009651"],
chart: {
animation: false,
renderTo: "stack2",
height : HEIGHT
},
xAxis: {
categories : CATEGORIES
},
title: {
style: {
display: 'none'
}
},
subtitle: {
style: {
display: 'none'
}
},
legend : false,
tooltip : false,
yAxis: {
max : null,
tickInterval : null,
tickLength : null,
stackLabels: {
enabled: true,
useHTML : false,
style : {
"fontWeight": "normal",
color : (THEME == "dark") ? "#b0b0b3" : "#000"
}
}
},
plotOptions: {
animation: false,
stickyTracking: false,
enableMouseTracking: false,
lineWidth: 0,
marker : {
enabled : false
},
column : {
dataLabels: {
enabled: true,
useHTML: true,
x : 0,
y : 0,
style : {
"fontWeight": "normal"
}
}
}
},
series : (function(){
var series = new Array();
var stack = [
{id : "cpu", alias : "CPU"}
];
for (var i = 0; i < stack.length; i++) {
//stack column 브러시 추가.
series.push({
name : stack[i].alias || stack[i].id,
id : stack[i].id,
lineWidth: 1,
data : (function(categories){
var data = [];
for (var i = 0; i < categories.length; i++) {
data.push(0);
}
return data;
})(CATEGORIES)
});
}
//circle
series.push({
type : "scatter",
name : "scatter",
id : "scatter",
marker: {
fillColor: '#FFFFFF',
lineWidth: 1,
lineColor: null
},
data : (function(b){
var data = [];
for (var i = 0; i < b.length; i++) {
data.push(0);
}
return data;
})(CATEGORIES)
});
console.log(series)
return series;
})()
});
var stack1 = Highcharts.chart(stack1Config);
var stack2 = Highcharts.chart(stack2Config);
var alarmTimeoutId = null;
var alarmTimeout = function(){
return setTimeout(function(){
var ACT_COLUMN = {
normal : [],
warning : [],
danger : [],
scatter : [] // success,warning,danger total value
};
var length = 20;
for (var i = 0; i < length; i++) {
var normalCnt = Math.round(Math.random()*100);
var warningCnt = Math.round(Math.random()*100);
var dangerCnt = Math.round(Math.random()*100);
ACT_COLUMN.scatter.push({ y: normalCnt+warningCnt+dangerCnt });
ACT_COLUMN.normal.push(normalCnt);
ACT_COLUMN.warning.push(warningCnt);
ACT_COLUMN.danger.push(dangerCnt);
}
for (var key in ACT_COLUMN) {
stack1.get(key).setData(ACT_COLUMN[key],false,false);
}
stack1.xAxis[0].setCategories(CATEGORIES);
ACT_COLUMN.scatter = null;
ACT_COLUMN.normal = null;
ACT_COLUMN.warning = null;
ACT_COLUMN.danger = null;
ACT_COLUMN = null;
var cpuData = [];
for (var i = 0; i < length; i++) {
var cpu = Math.round(Math.random()*100);
var color = "#009651";
if(cpu <= 50){
color = "#009651";
}else if(cpu <= 80){
color = "#ff9800";
}else{
color = "#ff1100";
}
cpuData.push({y : cpu, color : color });
}
var series = stack2.series;
var seriesLength = series.length;
for (var i = 0; i < seriesLength; i++) {
series[i].setData(cpuData,false,false);
}
stack2.xAxis[0].setCategories(CATEGORIES);
clearTimeout(alarmTimeoutId);
alarmTimeoutId = alarmTimeout();
}, 2000);
}
alarmTimeout();
</script>

Recveived error from phantomjs:ERROR: While rendering, there's is a timeout reached

I have some error while exporting the chart. I am using the exporting.js from Highcharts
Export PNG, JPEG, PDF received the below error.
Export SVG ok. But can't see the image.
Oops..,
Something went wrong while converting. recveived error from phantomjs:ERROR: While rendering, there's is a timeout reached
function renderChartPie(divId, chartType, chartTitle, chartCriteria, chartData, categories) {
var data = jQuery.parseJSON(chartData);
var cat = jQuery.parseJSON(categories);
var options = createOptionPie(divId, chartType, chartTitle, chartCriteria, cat);
options.series = [{
data : data
}];
var chart = new Highcharts.Chart(options);
}
function createOptionPie(divId, chartType, chartTitle, chartCriteria, categories) {
var options = {
colors : [ '#2f7ed8', '#0d233a', '#8bbc21', '#910000', '#1aadce',
'#492970', '#f28f43', '#77a1e5', '#c42525', '#a6c96a',
'#4572A7', '#AA4643', '#89A54E', '#80699B', '#3D96AE',
'#DB843D', '#92A8CD', '#A47D7C', '#B5CA92' ],
chart : {
renderTo : divId,
type : chartType,
events: {
load: function() {
var text = this.renderer.text('<br/>' + chartCriteria, 0, 445).css({
fontSize : 9
}).add();
var image = this.renderer.image('../../theme/50x71.png', 630, 409, 70, 51)
.add();
}
}
},
credits : {
enabled : false
},
legend : {
align: 'right',
verticalAlign: 'middle',
layout : 'vertical'
},
title : {
text : chartTitle
},
tooltip: {
formatter: function() {
return this.point.name +': '+ Highcharts.numberFormat(this.y,0) ;
}
},
xAxis : {
categories : categories
},
yAxis: {
},
plotOptions: {
pie: {
allowPointSelect : true,
showInLegend : true
}
},
series : []
};
return options;
}
The problem with timeout, because calling function (export) is limited. If problem will still appear, please prepare your own exporting server. Instructions are available here: http://www.highcharts.com/component/content/article/2-news/56-improved-image-export-with-phantomjs

Unexpected Highcharts results

I'm using highcharts as shown in examples but for some reason it flat out does not like my data. The only time I see a result is when I zoom out to all and then it only shows one point. Any clues as to what I'm doing wrong would be extremely appreciated.
how im getting my data:
$jsResult = array();
$arResults = $wpdb->get_results("SELECT tsDay, nPrice FROM sometable", ARRAY_A);
foreach($arResults as $key => $val){
//$val['nPrice'] = floatval($val['nPrice']);
//$jsResult[$key][0] = ($val['tsDay']*1000);
//$jsResult[$key][1] = intval($val['nPrice']);
//$strDate = date("Y/m/d", $val['tsDay']);
//$strDate = explode('/', $strDate);
$jsResult[$val['tsDay']] = '['.($val['tsDay']*1000).', '.$val['nPrice'].']';
}
$jsResult = "[\n".implode(",\n", $jsResult)."\n]";
?>
the chart:
$(document).ready(function() {
var data = <?php echo $jsResult; ?>;
// create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'graph',
zoomType: 'x'
},
navigator : {
series : {
data : data
}
},
rangeSelector : {
selected : 5 // All
},
tooltip: {
xDateFormat: '%Y-%m-%d %H:%M:%S'
},
xAxis : {
ordinal: true
},
series : [{
//type: 'candlestick',
name : 'data',
data : data,
dataGrouping : {
enabled : false
},
marker: {
enabled: true,
radius: 2
}
}]
});
Sample data from Highcharts that draws fine:
[1121212800000,38.35],
[1121299200000,40.75],
[1121385600000,41.55],
[1121644800000,41.49],
[1121731200000,43.19],
[1121817600000,43.63],
[1121904000000,43.29],
[1121990400000,44.00],
[1122249600000,43.81],
[1122336000000,43.63],
[1122422400000,43.99],
[1122508800000,43.80],
[1122595200000,42.65],
A sample of my data:
[1339736400000,1627.25],
[1339650000000,1613.50],
[1339563600000,1619.50],
[1339477200000,1603.50],
[1339390800000,1584.00],
[1339131600000,1576.50],
[1339045200000,1606.00],
[1338958800000,1635.00],
[1338526800000,1606.00],
[1338440400000,1558.00],
[1338354000000,1540.00],
[1338267600000,1579.50],
[1337922000000,1569.50],
here is what's wrong with your chart your array going backwords with time you start with jun 15 then 14 ,13 and so on
if you use reverse() you will get an array looks like this
var data = [ [1337922000000,1569.50], [1338267600000,1579.50] ,
[1338354000000,1540.00],[1338440400000,1558.00],
[1338526800000,1606.00],
[1338958800000,1635.00],[1339045200000,1606.00],
[1339131600000,1576.50],[1339390800000,1584.00],
[1339477200000,1603.50],[1339563600000,1619.50],]
this will make your chart works fine here is a working jsFiddle

Resources