Related
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>
I've implemented a polar chart in which each series has 4 values corresponding to 4 categories. When I export the chart csv, the category column contains polar coordinates. I would like to replace these with the corresponding category name. How do I do this?
Adding the categories to each series, had no effect. I also tried adding a categories property to the xAxis, but it had not effect. An xAxis.label formatter successfully returns the category name for each data polar coordinate.
const options = {
chart: {
polar: true,
},
title: {
text: '',
},
tooltip: {
valueDecimals: 2,
headerFormat: '<br/>',
},
legend: {},
pane: {
startAngle: 0,
endAngle: 360,
},
xAxis: {
tickInterval: 45,
min: 0,
max: 360,
labels: {
// eslint-disable-next-line
formatter: function() {
switch (this.value) {
case 45:
return '<b>Experience</b>'
case 135:
return '<b>Frictionless</b>'
case 225:
return '<b>Low Price</b>'
case 315:
return '<b>Brand</b>'
default:
return ''
}
},
},
},
yAxis: {
min: 0,
max: 10,
labels: {
format: '{}',
},
},
plotOptions: {
series: {
pointStart: 45,
pointInterval: 90,
},
column: {
pointPadding: 0,
groupPadding: 0,
},
},
series: kahnSeries,
}
You need to use categories property, but without options like: pointInterval, pointStart, min and max:
xAxis: {
categories: ['Experience', 'Frictionless', 'Low Price', 'Brand']
},
Live demo: http://jsfiddle.net/BlackLabel/z8cm1p39/
API Reference: https://api.highcharts.com/highcharts/xAxis.categories
To avoid changing the chart's current display, I wrapped the getCSV function and replaced the CSV category values. If there was a simpler way, please share it.
{
(function (H) {
H.wrap(H.Chart.prototype, 'getCSV', function (
proceed,
useLocalDecimalPoint
) {
// Run the original proceed method
const result = proceed.apply(
this,
Array.prototype.slice.call(arguments, 1)
)
const itemDelimiter = ','
const lineDelimiter = '\n'
const rows = result.split(lineDelimiter)
let newResult = ''
let rowCategories = false
rows.forEach((row, rowIndex) => {
const columns = row.split(itemDelimiter)
if (rowIndex === 0 && columns[0] === '"Category"') {
rowCategories = true
}
if (rowIndex > 0 && rowCategories) {
let newRow = formatter(columns[0])
columns.forEach((column, columnIndex) => {
if (columnIndex > 0) {
newRow += itemDelimiter
newRow += column
}
})
newResult += newRow
} else {
newResult += row
}
if (rowIndex < rows.length - 1) {
newResult += lineDelimiter
}
}
)
return newResult
})
}(Highcharts))
}
Following is my highcharts config, can you help me to why my alternate months are coming, and if i want to show every month, how do i do it ? Also, to change width of the bar if showing every month.
Highcharts.chart("energy_chart", {
chart: {
type: "column",
spacingBottom: 15,
spacingTop: 10,
spacingLeft: 10,
spacingRight: 10,
backgroundColor: "#f2f2f2",
events: {
load: function() {
var fin = new Date();
var finDate = fin.getDate();
var finMonth = fin.getMonth();
var finYear = fin.getFullYear();
var ini = new Date();
ini.setFullYear(ini.getFullYear() - 1);
var iniDate = ini.getDate();
var iniMonth = ini.getMonth();
var iniYear = ini.getFullYear();
if (this.yAxis[0].dataMax == 0) {
this.yAxis[0].setExtremes(null, 1);
}
//this.yAxis.set
console.log(new Date(Date.UTC(iniYear, iniMonth, iniDate)))
console.log(new Date(Date.UTC(finYear, finMonth, finDate)))
this.xAxis[0].setExtremes(
Date.UTC(iniYear, iniMonth, iniDate),
Date.UTC(finYear, finMonth, finDate)
);
},
drilldown: function(e) {
console.log('drilldown')
var charts_this = this;
var inidrillDate = new Date(e.point.x);
setTimeout(function() {
inidrillDate.setDate(0);
inidrillDate.setMonth(inidrillDate.getMonth());
var DateinidrillDate = inidrillDate.getDate();
var MonthinidrillDate = inidrillDate.getMonth();
var YearinidrillDate = inidrillDate.getFullYear();
var findrillDate = inidrillDate;
findrillDate.setMonth(findrillDate.getMonth() + 1);
findrillDate.setDate(findrillDate.getDate() - 1);
var DatefindrillDate = findrillDate.getDate();
var MonthfindrillDate = findrillDate.getMonth();
var YearfindrillDate = findrillDate.getFullYear();
console.log(Date.UTC(
YearinidrillDate,
MonthinidrillDate,
DateinidrillDate
))
console.log(Date.UTC(
YearfindrillDate,
MonthfindrillDate,
DatefindrillDate
))
charts_this.xAxis[0].setExtremes(
Date.UTC(
YearinidrillDate,
MonthinidrillDate,
DateinidrillDate
),
Date.UTC(
YearfindrillDate,
MonthfindrillDate,
DatefindrillDate
)
);
if (charts_this.yAxis[0].dataMax === 0) {
charts_this.yAxis[0].setExtremes(null, 1);
}
}, 0);
}
}
},
title: {
text: '<p className="energy_gen">Energy Generated</p>'
},
exporting: { enabled: false },
xAxis: {
type: "datetime",
labels: {
step: 1
},
dateTimeLabelFormats: {
day: "%e"
}
},
yAxis: {
title: {
text: "kWh"
}
},
credits: {
enabled: false
},
plotOptions: {
series: {
cursor: "pointer",
dataLabels: {
enabled: true,
format: "{point.y}"
},
color: "#fcd562",
point:{
events:{
click:function(event){
}
}
}
}
}
},
tooltip: {
formatter: function() {
if (this.point.options.drilldown) {
return (
"Energy generated: <b> " +
this.y +
"</b> kWh " +
"<br>" +
Highcharts.dateFormat("%b %Y", new Date(this.x))
);
} else {
return (
"Energy generated: <b> " +
this.y +
"</b> kWh " +
"<br>" +
Highcharts.dateFormat("%e %b %Y", new Date(this.x))
);
}
}
},
series: [{'data':obj.data,'name':obj.name,"color":"#4848d3"}],
drilldown: {
series: obj.data
}
});
Also, attaching the screenshot of the rendered highchart with drilldown.
,
Now drilldown graph(same sort a issue)
EDIT:
It turnsout to be a zoom issue, i.e if i zoomout enough, then it shows all points. So, how to show every point without zooimg out .
Working fiddle:
http://jsfiddle.net/gkumar77/w9ngp63u/5/
Use tickInterval property and set it to one month:
xAxis: {
type: "datetime",
tickInterval: 30 * 24 * 3600 * 1000,
labels: {
step: 1
},
dateTimeLabelFormats: {
day: "%e"
}
}
Live demo: http://jsfiddle.net/BlackLabel/q5coany2/
API: https://api.highcharts.com/highcharts/xAxis.tickInterval
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/
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>